Link to home
Start Free TrialLog in
Avatar of trey_carroll
trey_carroll

asked on

How do I read an XML comment using C# 3.5

I need to read the 1st comment in an xml file with the following format:

<root>
     <!--My comment-->
     <child1>blah</child2>
     ...
</root>

My XML is contained in an XDocument object in a C# 3.5 application.  

I just need to do something like;

//does not work
string s = xDoc.xpathSelectElement("\root\following::comment()[0]");

Thanks
<root>
     <!--My comment-->
     <child1>blah</child2>
     ...
</root>
 
//does not work
string s = xDoc.xpathSelectElement("\root\following::comment()[0]");

Open in new window

Avatar of abel
abel
Flag of Netherlands image

itneresting. But it cannot compile either. Is that really your source code? Just asking, because I would try to prevent hunting down a bug that a compiler could catch...
ah, it can compile. You are just unlucky with the words! \r is carriage return, \f is formfeed. Try this:

string s = xDoc.xpathSelectElement(@"\root\following::comment()[0]");
the @-prefix will make it unnecessary for you to have to escape the backslashes. Or you need to do this, instead:

string s = xDoc.xpathSelectElement("\\root\\following::comment()[0]");
but the,.... it is still not an XPath, so you won't get much. An XPath uses forward slashes. So, in the end, it becomes this:

string s = xDoc.xpathSelectElement("/root/following::comment()[0]");
Avatar of trey_carroll
trey_carroll

ASKER

The code was provided only as a guide.  The syntax is from an MSXML 2.0 example that I found on the web - provides as a "works sort of like this" guide.    I am looking for a new way since the way that I am trying does not work.
ASKER CERTIFIED SOLUTION
Avatar of abel
abel
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> The code was provided only as a guide.
ah, ok, thanks for telling ;-)

see above for a working example.
Thank you so much for such an excellent solution.  You might post a followup pointing out that line4 will cause a NullPointer Exception when the comment is found.   I'm not sure if I can do this - this is my 1st week using the service.  Thanks again - this information is nearly IMPOSSIBLE to locate on the net due to the facts that every tech site includes a section about comments,  there are so many articles on VS's new XML Comments in code - it makes it impossible to filter out the vast number of false positives.   You have made my day!