Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use XComment when reading in an XML document?

Tags:

c#

linq-to-xml

I'm using the following line to read in an XML document that may or may not have some comments bracketed by "<!-- -->" near the top of my XML file:

XDocument xe1 = XDocument.Load(filepath)

How do I read in the comments and store as a string?

I'm doing this in MS Visual Studio C#.

I know there's something called "XComment", but I can't find a simple example that uses it when reading in the XML (I can only find examples for creating a new XML file).

-Adeena

like image 931
adeena Avatar asked Dec 13 '08 21:12

adeena


1 Answers

Use this snippet to get all the comments from the XDocument:

var document = XDocument.Load("test.xml");

var comments =  from node in document.Elements().DescendantNodesAndSelf()
        where node.NodeType == XmlNodeType.Comment
        select node as XComment;

and this to parse only top-level comments:

var document = XDocument.Load("test.xml");

var comments = from node in document.Nodes()
           where node.NodeType == XmlNodeType.Comment
           select node as XComment;
like image 135
maxnk Avatar answered Nov 18 '22 06:11

maxnk