5

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

0

1 Answer 1

14

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Much more elegant than what I was trying. Thank you!
Instead of checking if node.NodeType == XmlNodeType.Comment and then selecting the node as XComment, you can use OfType: document.Nodes().OfType<XComment>(); for comments below the root: document.Root.Nodes().OfType<XComment>()

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.