Stephen Sulzberger’s Blog

April 2, 2008

asp.net: Handle comments in xml files

Filed under: asp.net,C#,Web development,xml — Stephen @ 7:29 pm

A small point, but asp.net’s XmlDocument doesn’t seamlessly handle xml comments when iterating through sub elements of an XmlNodeList. It’d be nice if XmlDocument didn’t read comments in the first place (I’d venture to say that xml comments aren’t meant to be read by compiled code), but I suppose it might be useful on some occasions to have the Load() method return everything in an xml doc. 

Not a big deal, but remember to handle comments explicitly any time an editable data file is consumed using the XmlDocument object.

For example, if expecting an xml document such as:

<?xml version="1.0" encoding="utf-8" ?>
<items>
  <item>
    <itemValue>value1</itemValue>
    <!--<itemValue>value2</itemValue>-->
    <itemValue>value3</itemValue>
  </item>
  <item>
    <!--<itemValue>value1</itemValue>-->
    <itemValue>value2</itemValue>
    <itemValue>value3</itemValue>
  </item>
</items>

The following approach (or similar) would need to be used in order to prevent the commented areas from being processed as bona fide elements:

    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(HttpContext.Current.Server.MapPath(@"~\App_Data\file.xml"));

    XmlNodeList nodeRoot = xmlDoc.GetElementsByTagName("item");

    for (int i = 0; i < nodeRoot.Count; i++)
    {
      XmlNodeList objNodes = nodeRoot[i].ChildNodes;

      foreach (XmlNode node in objNodes)
      {
        if (node.NodeType == XmlNodeType.Comment)
          continue;

        // Do something.
      }      
    }

In this case, “objNodes” actually contains 3 elements for each item – 2 elements with NodeType Element and 1 element with NodeType Comment. If this is not handled properly in the iterations, it is possible for the code (or general routine) to fail supposing that an element is commented out with the intention for it to not be processed.

For more information: http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.value.aspx

Create a free website or blog at WordPress.com.