Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

Broker Server

The broker server is divided into the following tasks:

  • Listening to orders

  • Accepting the client request

  • Reading the XML file into XML DOM

  • Selecting a command

  • Invoking the action

  • Sending the response to the client and cleaning up

Listening to Orders

The broker server listens to the client order through TCP. It utilizes the TcpListener class for listening and accepting connections from the client. The TcpListener class uses the Bind method to bind to an IP address and port.

string ipAddr = "";
int port = 12345;
TcpListener orderListener = new TcpListener(IPAddress.Parse(ipAddr),

// start listening to the socket

After creating the object of the TcpListener class, we start listening to the socket by calling the Start() method. The Start() method internally calls the socket's Bind() method to bind to the end point we provided in the constructor.

Accepting the Client Request

The Start() method continues to listen to the port until some client tries to connect. We can use the TcpClient's Pending() method to determine whether there are any pending client requests. If Pending() returns true, some client is trying to connect with the server. In that case, we call the AcceptTcpClient() method to accept a pending connection request; otherwise, we can skip this step and do other tasks instead of blocking the thread.

// accepting client connection
// we take socketAccepted as an instance of TcpClient,
// which is then used to communicate with the client
if (orderListener.Pending())
socketAccepted = orderListener.AcceptTcpClient();

Reading the XML File into XML DOM

The next step after establishing a connection with the client is to receive the order file. The order file is transferred as a stream; therefore, to read it back from the client we use the StreamReader's ReadLine() method:

// reading XML from client
StreamReader readerStream =
       new StreamReader(socketAccepted.GetStream());
String xmlFile = readerStream.ReadLine();

The complete XML file is now in the xmlFile string. The XmlDocument's LoadXML() method is then used to read the string into DOM:

// converting string to XML format
XmlDocument orderXml = new XmlDocument();

Selecting a Command

A factory is a common interface through which we can facilitate the creation of objects. It's a single place where the object instantiation services are provided, instead of spanning the system. Whenever you want to add a new type to the system, you just have to edit the code in the factory. This design pattern belongs to the Creational category, which involves the details of object creation, so the code isn't dependent on what types of objects there are and thus doesn't have to be changed if a new type is added to the system.

The key to making a factory method is to build an abstract base class and define a static factory method in it. This static method will serve as the method to create different objects.

The abstract base class used in the sample is as follows:

// the top level abstract class
abstract class Action
  public static string StatusMessage;

  public abstract void InvokeAction(XmlDocument xmlDoc);

  public XmlNode getXmlNode(XmlDocument xmlDoc, string strQuery)
   return xmlDoc.SelectSingleNode(strQuery);

  public static Action ActionFactory(string actiontype)
   if (actiontype.Equals("saveinvoice"))
     return new SaveAction();
   else if (actiontype.Equals("mailinvoice"))
     return new MailAction();
     return new SaveAction(); // default action


Apart from the static factory method, the class consists of some other methods that are inherited by the child classes. The factory method ActionMethod() takes an argument that allows it to determine the type of the action object to create. Based on the argument, the method returns the appropriate object to the caller. If we want to add another type to the system, we make another class implementing the abstract Action class. The code inside the ActionFactory() method is changed to add another if check, to compare the new type to the argument and subsequently return the new type's object.

Following are the two classes implemented in this example:

// implementation of the SaveAction class
class SaveAction : Action

// implementation of the MailAction class
class MailAction : Action

Both of these classes implement the Action abstract class.

Invoking the Action

After getting our required object instance through the object factory, we call the InvokeAction() method of the appropriate object. We implemented two different actions in our XML file and in the server: MailAction and SaveAction. The following sections describe both.


The MailAction class implements the procedure of sending an email with the order to the specified email address in the XML file. To implement this method, we get the required fields from the XML file, and then use the .NET System.Web.Mail classes to send the email.

The required fields from the XML file are fetched by using XPath. (See w3schools.com for a good XPath tutorial.) XPath allows the application to locate one or more nodes from an XML document. It provides the syntax for performing basic queries on the XML document.

We used the XmlDocument's SelectSingleNode() method to select the node from an XML document using the XPath query. For example, we use the following XPath query to find the to name in the XML file:


The location path can be absolute or relative. An absolute location starts with a slash (/).

The XPath also contains functions to retrieve an element node, text, or attribute. The text() is used to retrieve the node text of the node on which it's called. The path just described returns the text between the <to></to> tags. The code below retrieves the text inside the toName and toEmail text elements:

XmlNode toName = xmlDoc.SelectSingleNode ("/message/header/to/text()");
XmlNode toEmail = xmlDoc.SelectSingleNode ("/message/header/toemail/text()");

To retrieve an attribute, we use the "at" (@) character with the attribute name:

// get invoice number
XmlNode invoiceNumber =
xmlDoc.SelectSingleNode ("/message/body/saveinvoice/invoice/@number");

This code retrieves the number attribute from the invoice tag. The SelectSingleNode() method returns an XmlNode object. The Value property of the XmlNode class returns the value of the node.

After retrieving the required values from the XML document, we transform the XML document into HTML by using the XSL transformation. .NET provides the class XslTransform for transforming XML using an XSL file. (See www.w3schools.com for an XSL tutorial.) The XSL file is shown below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"

<xsl:template match="/">
<title>Order Page</title>
<b>To: </b><xsl:value-of select="message/header/to"/> &lt;
<xsl:value-of select="message/header/toemail" />&gt; <br/>
<b>From: </b><xsl:value-of select="message/header/from"/> &lt;
<xsl:value-of select="message/header/fromemail" />&gt; <br/>
<p><b>Invoice No.: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/@number" />
<br/><b>Date: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/@date" /></p>
<b>Name: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/address/name"/>
<b>Street: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/address/street"/>
<b>City: </b>
<xsl:value-of select="message/body/saveinvoice/invoice/address/city" />
<b>Country: </b>
<xsl:value-of select="message/body/saveinvoice/invoice/address/@country"/>


To transform an XML document using XSL, we first created an object of the XslTransform class and then called its Load method to load the XSL file into the object. The real transformation is performed in another function called Transform(), which takes the XML document and the output stream as parameters. Transform() reads the XML file from the XmlDocument object, applies the transformation, and stores the result in the output stream specified in the last parameter.

After executing the following piece of code, the StringWriter's object has the transformed HTML file:

// transforming the XML file
XslTransform orderXsl = new XslTransform();

// generating the transformed file and
// reading into TextWriter
StringWriter orderWriter = new StringWriter();

The last step in this action is to send the HTML through email to the recipient specified in the XML document. The recipient's name is retrieved using the SelectSingleNode() method of the XmlDocument class.

// Code to send invoice as email
MailMessage msg = new MailMessage();

// specifying the message body as HTML
msg.BodyFormat = MailFormat.Html;

// specifying the message recipient and sender
msg.To = toEmail.Value;
msg.From = fromEmail.Value;

msg.Subject = "Invoice No." + invoiceNumber.Value
        + " from " + toName.Value;

string body = orderMessage;

msg.Body = body;

// sending email through SMTP Server
SmtpMail.SmtpServer = "smtp.abc.com";

The code above is applied to send email through the SMTP server. The message body and subject are constructed using the MailMessage class in the System.Web.Mail namespace. Because we're sending the email in HTML format, we set the BodyFormat property of the MailMessage class. Similarly, we set the appropriate fields for body, subject, sender, and recipient addresses. After completing the body of the message, the Send() method of the SmtpMail class is used to send the message to the SMTP server.


Notice the SMTP server specified in the SMTPServer property, which is used to route email directly to the specified SMTP address. If we don't specify any SMTP address, the Windows SMTP Service is used for sending email.


The SaveAction class implements the saving mechanism. The method saves the XML file on the filesystem. First, the appropriate values required are retrieved from the XML document, using the XPath queries. After that, the Save() method of the XmlDocument class is used to save the document.

// encapsulate invoice into XML
XmlNode invoiceNode = 

XmlNode invoiceNumber =

// loading a sub portion of the XML file
XmlDocument invoiceDoc = new XmlDocument();

// saving the XML DOM to a file
invoiceDoc.Save(invoiceNumber.Value + ".xml");

The XmlDocument's OuterXml property gets the markup representing the current node and all its children. The invoice number is used as the filename.

Sending the Response to the Client and Cleaning Up

After processing the XML document, the last step that's required for the server is to send a response back to the client about the status of the order. The response is created dynamically using the XmlTextWriter class.

The XmlTextWriter class contains methods to create elements, attributes, nodes, and all the other parts in an XML document. The XmlTextWriter constructor requires a stream to which all the output is written. This stream is passed to the XmlTextWriter's object through the constructor. Next, the WriteStartDocument() method is called to create the basic XML tag in memory, and WriteStartElement() and WriteAttributeString() write an element and an attribute, respectively. To create a node with child nodes, we use WriteStartElement(). To define the last node in the tree, we use WriteElementString(). To close the tag, the WriteEndElement() method is called for each opened tag.

// stream XML output to StringWriter
StringWriter xmlResponse = new StringWriter();
XmlTextWriter xWriter = new XmlTextWriter(xmlResponse);

// start the document

// write the root element

// get the toAddress
XmlNode toName = xmlDoc.SelectSingleNode("/message/header/to/text()");
XmlNode toEmail =

// get the fromAddress
XmlNode fromName =
XmlNode fromEmail =

// get the invoice number
XmlNode invoiceNumber =

xWriter.WriteAttributeString("number", invoiceNumber.Value);

xWriter.WriteElementString("toname", toName.Value);
xWriter.WriteElementString("toemail", toEmail.Value);

xWriter.WriteElementString("fromname", fromName.Value);
xWriter.WriteElementString("fromemail", fromEmail.Value);

xWriter.WriteElementString("message", Action.StatusMessage);


// close the root element


The XmlTextWriter is flushed after constructing the body. The StringWriter is now ready to be transferred to the client side, using the NetworkStream's Write() method. The Write() method accepts a byte array; therefore, we first convert the string into bytes using the GetBytes() method:

// sending XML file to client
// assume that writerStream is an object of NetworkStream
byte [] dataWrite = Encoding.ASCII.GetBytes(xmlResponse.ToString());

After sending the response, the listener socket is stopped and the client socket is closed to finish the server's task and end the application.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020