Home > Articles > Web Services > XML

Like this article? We recommend

Putting It Together

Remember the namespace that we created? If not, then you need not worry, because it still exists. This is mostly for reference purposes, but in Listing 2 you will find a new and improved namespace that incorporates editing functionality. Copy and paste that into a file named contacts_lib.cs under the Web site's /bin directory.

Listing 2: Test Namespace with Editing Functionality

namespace test
{
   using System;
   using System.Collections;
   using System.Xml;
   using System.Xml.XPath;
   using System.Web;

   public class Contact
   {
     public Contact()
     {
        szFirstName = String.Empty;
        szLastName  = String.Empty;
        szMiddleName = String.Empty;
        szGender   = String.Empty;
        szInitials  = String.Empty;
        szKeywords  = String.Empty;
        
        oAddresses = new Hashtable();
        oPhones  = new Hashtable();
     }

     public Contact(XPathNavigator oNav, String szId)
     {
        // Grab the contact info 
//and initialize the data members.
       String szQry = "personal_information/[ccc]
               contacts/entry[@id='" + szId + "']";
       XPathNodeIterator oIterator = oNav.Select(szQry);
       oIterator.MoveNext();


      XPathNodeIterator oName = oIterator.Current.Select("./name");
      oName.MoveNext();

       szFirstName = GetAttributeText(oName.Current, "first");
       szMiddleName = GetAttributeText(oName.Current, "middle");
       szLastName  = GetAttributeText(oName.Current, "last");
       szInitials  = String.Empty;
       szKeywords  = String.Empty;

       if (GetAttributeText(oName.Current, "gender") == "f")
       {
          szGender = "Female";
       } else {
          szGender = "Male";
       }


       oAddresses = new Hashtable();
       Address oHome = new Address(oIterator.Current, "home");
       Address oWork = new Address(oIterator.Current, "work");
       oAddresses.Add("home", oHome);
       oAddresses.Add("work", oWork);
       oPhones = new Hashtable();

      PhoneNumber oPH = new PhoneNumber(oIterator.Current, "home");
      PhoneNumber oPW = new PhoneNumber(oIterator.Current, "work");
       oPhones.Add("home", oPH);
       oPhones.Add("work", oPW);
     }
     
     public PhoneNumber GetPhoneNumber(String szType)
     {
        return (PhoneNumber) oPhones[szType];
     }

     public Address GetAddress(String szType)
     {
        return (Address) oAddresses[szType];
     }

     private String GetAttributeText(XPathNavigator nav, [ccc]
                       String szName)
     {
       String szRetval = String.Empty;
       nav.MoveToAttribute(szName, "");
       szRetval = nav.Value;
       nav.MoveToParent();
       return szRetval;
     }
     
     public String szFirstName;
     public String szMiddleName;
     public String szLastName;
     public String szGender;
     public String szKeywords;
     public String szInitials;

     private Hashtable oAddresses;
     private Hashtable oPhones;
   }

   
   public class Address
   {
     public Address()
     {
        szState = String.Empty;
        szCity = String.Empty;
        szZip  = String.Empty;
     }

     public Address(XPathNavigator oNav, String szType)
     {
        try
        {
          szState = String.Empty;
          szCity = String.Empty;
          szZip  = String.Empty;

          XPathExpression oExpr;
          String szExpr = String.Empty;

          szExpr = "./address[@type='" + szType + "']/line";
          oExpr = oNav.Compile(szExpr);
          
          ContactCompare oAddrCompare = new ContactCompare();

          // Add a comparer to do a string compare
          oExpr.AddSort("@seq", (IComparer)oAddrCompare);

          XPathNodeIterator oIterator = oNav.Select(oExpr);
          int x = 0;

          aLines = new String[oIterator.Count];

          while (oIterator.MoveNext())
          {
             aLines[x] = oIterator.Current.Value;
             x++;
          }

          szExpr = "./address[@type='" + szType + "']/city";
          
          oIterator = oNav.Select(szExpr);
          oIterator.MoveNext();
          szCity = oIterator.Current.Value;
          
          szExpr  = "./address[@type='" + [ccc]
                 szType + "']/state";
          oIterator = oNav.Select(szExpr);
          oIterator.MoveNext();

          szState = oIterator.Current.Value;

          szExpr = "./address[@type='" + [ccc]
                szType + "']/zipcode";
          oIterator = oNav.Select(szExpr);
          oIterator.MoveNext();
        
          szZip = oIterator.Current.Value;
          oIterator.Current.MoveToParent();
        }
        catch (ArgumentException ex)
        {
          String blah = ex.Message;
          szState = String.Empty;
          szCity = String.Empty;
          szZip  = String.Empty;
        }
     }

     public String[] aLines;
     public String szState;
     public String szCity;
     public String szZip;
   }

   class ContactCompare : IComparer
   {
     public int Compare(Object First, Object Second)
     {
        String s1 = (String) First;
        String s2 = (String) Second;

        return s1.ToString().CompareTo(s2.ToString());
     }

   }

   public class PhoneNumber
   {
     public PhoneNumber(String szAc, String szNum)
     {
        szACode = szAc;
        szNumber = szNum;
     }

     public PhoneNumber(XPathNavigator oNav, String szType)
     {
        
        String szExpr = String.Empty;
        szExpr = "./phone[@type='" + szType + "']";

        XPathNodeIterator oIterator = oNav.Select(szExpr);

        oIterator.MoveNext();
        
        szACode = GetAttributeText(oIterator.Current, "acode");
       szNumber = GetAttributeText(oIterator.Current, "number");
     }

     private String GetAttributeText(XPathNavigator nav, [ccc]
                        String szName)
     {
       String szRetval = String.Empty;
       nav.MoveToAttribute(szName, "");
       szRetval = nav.Value;
       nav.MoveToParent();
       return szRetval;
     }
     
     public String szACode;
     public String szNumber;
   }

   // Only manages one contacts xml file at a time. 
   public class ContactManager
   {
     public ContactManager(String szFile, TraceContext Trc)
     {
        Trace = Trc;
        szFilePath = szFile;
        // Initialize the XPath classes.
        oDoc = new XmlDocument();

        LoadData();
     }

     
     public bool AddContact(Contact oSave)
     {
        try
        {
   
        // Currently only adds these nodes. 
        //<entry id="0" initials="jxd">
        //<name first="John" middle="X." last="Doe" gender="m" />
        //</entry>
          String szQry = "personal_information/contacts";
          XmlNode oRoot = oDoc.SelectSingleNode(szQry);
          XmlNode oEntry = oDoc.CreateElement("entry");
          
          XmlAttribute oId  = oDoc.CreateAttribute("id");
         XmlAttribute oInit = oDoc.CreateAttribute("initials");

          oId.Value  = Convert.ToString(iContactCtr);
          oInit.Value = oSave.szInitials;

          oEntry.Attributes.Append(oId);
          oEntry.Attributes.Append(oInit);
          XmlNode oName = oDoc.CreateElement("name");

          XmlAttribute oFirst = oDoc.CreateAttribute("first");
          XmlAttribute oMid = oDoc.CreateAttribute("middle");
          XmlAttribute oLast  = oDoc.CreateAttribute("last");
          XmlAttribute oGndr = oDoc.CreateAttribute("gender");

          oFirst.Value = oSave.szFirstName;
          oMid.Value  = oSave.szMiddleName;
          oLast.Value  = oSave.szLastName;
          oGndr.Value = oSave.szGender;

          oName.Attributes.Append(oFirst);
          oName.Attributes.Append(oMid);
          oName.Attributes.Append(oLast);
          oName.Attributes.Append(oGndr);

          oRoot.AppendChild(oEntry);
          String szCtr = Convert.ToString(iContactCtr);
          Trace.Write("AddContact", szCtr);
          
          Flush();

          Trace.Write("AddContact", "Contact added");

        }
        catch (Exception ex)
        {
          String blah = ex.Message;
          Trace.Write("AddContact", blah);
          return false;
        }
        
        return true;
     }

     public bool DeleteContact(String szId)
     {
           String szQry = "personal_information/contacts/[ccc]
                     entry[@id=\""+ szId + "\"]";
        XmlNode oDelete = oDoc.SelectSingleNode(szQry);
        
        if (oDelete != null)
        {
          try
          {
           String szCnQry = "personal_information/contacts";
           XmlNode oContacts = oDoc.SelectSingleNode(szCnQry);
           oContacts.RemoveChild(oDelete);

            // Renumber the ids to avoid collisions.
           String sQy = "personal_information/contacts/" +[ccc]
                  "entry";

           XmlNodeList oNodes = oDoc.SelectNodes(sQyy);
             
            if (oNodes != null)
            {
              Trace.Write("DeleteContact","oNodes.length [ccc]
              = " + Convert.ToString(oNodes.Count));
              int x = 0;

              foreach(XmlNode oNode in oNodes)
              {
                String szNew = Convert.ToString(x);
                oNode.Attributes["id"].Value = szNew;
                x++;
              }
            } else {
              Trace.Write("DeleteContact", "oNodes is [ccc]
                  null. can't renumber the entries");
            }
          }
          catch (Exception ex)
          {
             String blah = ex.Message;
             Trace.Write("DeleteContact", blah);
             return false;
          }

          return true;
        } else {
          return false;
        }
     }

     public Contact GetContact(String szId)
     {
        Contact pTemp = new Contact(oNav, szId);
        return pTemp;
     }

     public Contact GetContact(int Id)
     {
        Contact pTemp = new Contact(oNav, Convert.ToString(Id));
        return pTemp;
     }

     public int Count()
     {
        return iContactCtr;
     }

     public bool Flush()
     {
        oDoc.Save(szFilePath);
        LoadData();
        
        return true;
     }

     private void LoadData()
     {
        oDoc.Load(szFilePath);
        oNav = oDoc.CreateNavigator();
        oNav.MoveToRoot();

        // Get a count of all entries.
        String szQry = "personal_information/contacts/entry";
        XPathNodeIterator oIterator = oNav.Select(szQry);
        iContactCtr = oIterator.Count;
     }

     private XPathNavigator oNav;
     private XmlDocument  oDoc;
     private int      iContactCtr;
     private String     szFilePath;
     private TraceContext  Trace;
   }

}

Looking closer at the DeleteContact member, we see how easy it is to complete a delete for this XML. The ID attribute from the entry node is used to communicate which node to delete. Then it is selected, and RemoveChild is called from an XmlNodeList object that contains the specified node. The only thing that is missing is the actual save to disk. Each time delete is called, it only updates the current XML in memory for the specified instance of ContactManager.

NOTE

A Flush() member was provided in the namespace in Listing 2 so that UI code could save after completing all deletes.

Deleting nodes is very easy, but one thing is still missing from your arsenal of XML editing knowledge. The ability to add data is just as important as deleting it. Without it, we could never reinsert long-lost friends or acquaintances back into our data, if required. Adding nodes to XML requires a bit more work than deleting them on our part. The basic method calls used are from a number of classes (System.Xml namespace), as follows:

  • CreateElement()
  • CreateAttribute()
  • set property Value
  • Attributes.Append()
  • AppendChild()

(Repeat process as required.)

The only thing that has not been done in AddContact is to set the node value itself. That task can be accomplished by setting the value of the node returned from CreateElement. With the ContactManager class, a slightly different approach must be taken toward adds so that the XML business is abstracted away from the page UI. In this case, we utilize the Contact data instance class to provide a method to communicate the data to the ContactManager class method AddContact. Once all the proper nodes are created and appended properly, we then use the Flush() method to save the DOM to disk. Of importance is that this differs from DeleteContact because only one contact can be added at a time. This work is monotonous and best abstracted from the UI, although the UI has a bit of work ahead of it to represent this data in HTML to the user. Let's go on to a small example to help illustrate the usage of these new namespace features.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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