12

I have got some XML files that contain comments above the nodes. When I am reading the file in, as part of the process I would like to get the comment out as well. I know you can write a comment to the file using XmlComment, but not sure how to read them back out.

My XML looks similar to this:

<Objects>
  <!--Comment about node-->
  <GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>
    <info job="SAVE" person="Joe" />    
    <info job="SAVE" person="Sally" />       
  </GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>
  <!--Another Comment about node-->
  <GUID-bf2401c0-ef5e-4d20-9d20-a5844113284112>
    <info job="SAVE" person="John" />    
    <info job="SAVE" person="Julie" />       
  </GUID-bf2401c0-ef5e-4d20-9d20-a5844113284112>

3
  • 1
    Important missing detail: What is the code you use to "read the file in"? Commented Jun 8, 2011 at 11:28
  • Well .. how are you reading this Commented Jun 8, 2011 at 11:29
  • Check this answer Commented Jun 8, 2011 at 11:34

6 Answers 6

17

Try this:

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = false; 
using (XmlReader reader = XmlReader.Create("input.xml", readerSettings))
{
    XmlDocument myData = new XmlDocument();
    myData.Load(reader);
    // etc...
}

To read comments:

XmlReader xmlRdr = XmlReader.Create("Test.XML");
// Parse the file
while (xmlRdr.Read())
{
    switch (xmlRdr.NodeType)
    {
        case XmlNodeType.Element:
            // You may need to capture the last element to provide a context
            // for any comments you come across... so copy xmlRdr.Name, etc.
            break;
        case XmlNodeType.Comment:
            // Do something with xmlRdr.value
Sign up to request clarification or add additional context in comments.

4 Comments

false is the default value for IgnoreComments
@V4vend: Even so, both in this answer and in real code it is a good idea to set it explicitly.
Worked a treat, i never realized the nodes had types like that.
What is comment is placed outside root element, in this case <Objects>? Could it be read and parsed?
14

Using System.Xml.Linq:

var doc = XElement.Load(fileName);
var comments = doc.DescendantNodes().OfType<XComment>();

foreach (XComment comment in comments)
   ...

Comments

3

They are a part of the child nodes of the containing node as all other nodes: http://msdn.microsoft.com/en-us/library/system.xml.xmlcomment.aspx

Comments

2

I know the question is very old, but yesterday I had the same problem. So here is my solution:

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = false;
settings.IgnoreComments = false;
XmlReaderSettings settings2 = new XmlReaderSettings();
settings2.IgnoreWhitespace = false;
settings2.IgnoreComments = false;
XmlReader xmlreaderOriginalCfg = XmlReader.Create(@"C:\...xml", settings);
XmlReader xmlreaderVerificationCfg = XmlReader.Create(@"C:\....xml", settings);

XmlDocument myData = new XmlDocument();
myData.Load(xmlreaderOriginalCfg);
XmlDocument myData2 = new XmlDocument();
myData2.Load(xmlreaderVerificationCfg);

XmlNode parentNode = myData.SelectSingleNode("/configuration/appSettings");

foreach (XmlComment comment in myData2.SelectNodes("//comment()"))
{
     XmlComment importedCom = myData.CreateComment(comment.Value);
     parentNode.AppendChild(importedCom);

     foreach (XmlNode node in myData2.DocumentElement.SelectNodes("/configuration/appSettings/add"))
     {
          XmlNode imported = myData.ImportNode(node, true);
          parentNode.AppendChild(imported);
     }
}
myData.Save(this.pathNew);

Maybe it helps somebody

Comments

0

I stored your XML into a file, here is the code sample.

        XmlDocument document = new XmlDocument();
        document.Load("test.xml");
        foreach (XmlComment comment in document.SelectNodes("//comment()"))
        {
            Console.WriteLine("Comment: \"{0}\".", comment.Value);
        }

Comments

0

Some sample code on how to access comments hope this helps

using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<Objects><!--Comment about node--><othernode/><!--Some more comment--></Objects>");

    XmlNode root = doc.FirstChild;
    if (root.HasChildNodes)
    {
      for (int i=0; i<root.ChildNodes.Count; i++)
      {
        if(     root.ChildNodes[i] is XmlComment)
            Console.WriteLine(root.ChildNodes[i].InnerText);
      }
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.