Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Loading, Parsing, and Generating XML using C# and the System.XML Namespace
By Jesse Smith

Rate This Article: Add This Article To:

Loading, Parsing, and Generating XML using C# and the System.XML Namespace - ' Reading Values from an '
( Page 3 of 3 )

XML Document">

Reading Values from an XML Document

Sometimes, you need to extract values from an XML document produced by another application, which your application will use.

To do this, the XML Namespace provides a class called XmlTextReader.

It contains methods for reading your XML doc's elements and attributes.

The example below illustrates the process by reading values from the author.xml file created above.

Create a new type called reader, which you use to access the methods of the XmlTextReader class to be used on the file author.xml.



string xmlFilename = Server.MapPath("Authors.xml"))
XmlTextReader reader = new XmlTextReader(xmlFilename);

Tell the reader to ignore all the document's white spaces:

reader.WhitespaceHandling = WhitespaceHandling.None;

Parse the file by iterating through the XML elements and attributes. We check to see when the reader encounters the Authors element; when it does, have it get the element's attributes using the GetAttribute method.

while (reader.Read()) {
     switch (reader.NodeType) {
       case XmlNodeType.Element:
    if (reader.Name == "Authors") {
      Response.Write("Author ID: " +
        reader.GetAttribute("au_id") + "<br>");
      Response.Write("Author Name: " +
       reader.GetAttribute("au_fname") +
        " " + reader.GetAttribute("au_lname") + "<br>");
    }
         break;
       case XmlNodeType.Text:
         Response.Write("Author Title: " +
           reader.Value + "<br>");
         break;
     }       
  }
reader.Close();

After executing the code above, the following results are written to the screen:

Author ID: 409-56-7008
Author Name: Abraham Bennet
Author Title: The Busy Executive's Database Guide

By adding other conditional statements, you can parse any XML file to display or store the results to another file or database.

Adding Elements and Attributes

To add new elements and attributes to your XML file, you use the XmlElement, XmlAttribute, and XmlText classes. In this next example, you'll add a new Authors element and its corresponding attributes to the Authors.xml file.

XmlDocument doc = new XmlDocument(); 
doc.Load(Server.MapPath("Authors.xml"));

Create a new element type called newElem. Call the CreateElement method of the doc type class to associate this element with the newElem type:

XmlElement newElem = doc.CreateElement("Authors");

Add the attributes to the new Authors element by creating a new XmlAttribute type for each attribute. Use the CreateAttribute method of the doc type to associate the new attribute with its corresponding attribute type. Use the Append property to add the attribute to the document.

   XmlAttribute au_id = doc.CreateAttribute("au_id");
      au_id.Value = "409-56-7009";
      newElem.Attributes.Append(au_id);
      
      XmlAttribute au_lname = doc.CreateAttribute("au_lname");
      au_lname.Value = "Smith";
      newElem.Attributes.Append(au_lname);  
      
      XmlAttribute au_fname = doc.CreateAttribute("au_fname");
      au_fname.Value = "Tom";
      newElem.Attributes.Append(au_fname); 

Create a new child element called Title using the InnerXml method. Add the title text to the element using a new type called txtNode, derived from class XmlText. Append the new element and text (or value) using the FirstChild and AppendChild properties.

   newElem.InnerXml = "<Title></Title>";
      XmlText txtNode = doc.CreateTextNode("Where Does The Time Go");
      newElem.FirstChild.AppendChild(txtNode);
      doc.DocumentElement.AppendChild(newElem);      
        
      doc.Save(Server.MapPath("Authors.xml"));

Modifying Elements and Attributes

It's no surprise the same classes which you use to add elements and attributes also handle making changes to them. This example changes an author id and title:

XmlDocument doc = new XmlDocument(); 
doc.Load(Server.MapPath("Authors.xml")); 

The SelectNodes class (derived from the Document Object Model) is used to index into the file. Each slash represents a level in the element hierarchy.

XmlNodeList nodeList = doc.SelectNodes("//Authors"); 
foreach (XmlNode node in nodeList) {

The code below checks for the author id we want to change. Once it is found, we set the value of the au_id attribute to the new author id.

if (node.Attributes["au_id"].Value == " 409-56-7009 ") {
  node.Attributes["au_id"].Value = " 409-56-7030";	     
    }

Now we check for the title we want to change. Once if is found, we use the InnerText property to make the change.

if (node.FirstChild.InnerText == " Where Does The Time Go") {
  node.FirstChild.InnerText = "Vacant Title";
    }
  }
  doc.Save(Server.MapPath("Authors.xml"));

You can see how easy it is to expand on this by adding other conditions. You can change the value of all first child elements in the document by leaving out the IF condition. You can use the ChildNodes property to flag other elements beyond the first child element.

Removing Elements and Attributes

To remove elements, the RemoveChild class is used. Using the code above, we can easily make a small change to have all title elements removed from the file.

XmlDocument doc = new XmlDocument(); 
doc.Load(Server.MapPath("Authors.xml")); 
XmlNodeList nodeList = doc.SelectNodes("//Authors"); 
 foreach (XmlNode node in nodeList) { 
                 node.RemoveChild(node.SelectSingleNode("Title"));
   }
        
doc.Save(Server.MapPath("Authors.xml"));

Again, we could expand on this by adding other conditions to flag certain elements we want removed.

Removing attributes is a little more complicated. We have to set up an attribute collection for the element using the XmlAttributeCollection class. This collection stores all of the element's attributes in a temporary array that can be indexed by name or position.

The example below uses the code above, but this time removes the au_fname attribute from each element.

XmlDocument doc = new XmlDocument(); 
doc.Load(Server.MapPath("Authors.xml")); 
XmlNodeList nodeList = doc.SelectNodes("//Authors"); 
foreach (XmlNode node in nodeList) { 

We set up an attribute collection here for each element, and find the au_name attribute and remove it by using the Remove method of the XmlAttributeCollection class.

XmlAttributeCollection attrColl = node.Attributes;
     attrColl.Remove(attrColl["au_fname"]);
  	}
      
doc.Save(Server.MapPath("Authors.xml"));

In this article, I gave you a good start in slicing-and-dicing your XML documents. Other, less common classes are also available; they can be useful depending on what you need to accomplish. There are also different ways to use the same classes to achieve the same results.

The above examples can also serve as a good template or starting point for populating XML documents from a database. By replacing the static parameters with variables from a database, you can quickly make your application XML-aware.



 
 
>>> More Microsoft Languages Articles          >>> More By Jesse Smith