Preserving comments with XmlDocument.Load
-
I am reading an XML file in using XmlDocument. The XML file may contain comments that I want to capture and deal with. When I look at the nodes that XmlDocument returns, though, there are no XmlComment nodes. I can see how to create comments using the CreateComment method, but how do I preserve them when I read them in?
-
I am reading an XML file in using XmlDocument. The XML file may contain comments that I want to capture and deal with. When I look at the nodes that XmlDocument returns, though, there are no XmlComment nodes. I can see how to create comments using the CreateComment method, but how do I preserve them when I read them in?
Hi Lannie, XmlDocument contains all comments if you load an xml document. But the most access functions ignore comments. But following simple code shows message boxes with both comments:
/\* <test> <!-- super tip --> <tip>Close a application with the cross in the right top corner of the window.</tip> <!-- stupid tip --> <tip>1+2=3</tip> </test> \*/ string xmlstring = @**"<test><!-- super tip --><tip>Close a application with the cross in the right top corner of the window.</tip><!-- stupid tip --><tip>1+2=3</tip></test>"**; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlstring); XmlNode node = doc.SelectSingleNode("/test"); for (XmlNode subnode = node.FirstChild; subnode != null; subnode = subnode.NextSibling) { XmlComment comment = subnode as XmlComment; if (comment != null) MessageBox.Show(comment.Value); }
That the XmlDocument contains all comments you see if you look at the OuterXml property of the XmlDocument or save the document in a file. The Comment direct before a XmlElement you get with element.PreviousSibling as XmlComment. The Comment direct behind a XmlElement you get with element.NextSibling as XmlComment. Hope it's help Niedzi