Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content of XML node using c#

Tags:

c#

xml

xpath

simple question but I've been dinking around with it for an hour and it's really starting to frustrate me. I have XML that looks like this:

  <TimelineInfo>
    <PreTrialEd>Not Started</PreTrialEd>
    <Ambassador>Problem</Ambassador>
    <PsychEval>Completed</PsychEval>
  </TimelineInfo>

And all I want to do is use C# to get the string stored between <Ambassador> and </Ambassador>.

So far I have:

XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");

which selects the note just fine, now how in the world do I get the content in there?

like image 783
Adam S Avatar asked Jun 03 '10 15:06

Adam S


1 Answers

May I suggest having a look at LINQ-to-XML (System.Xml.Linq)?

var doc = XDocument.Load("C:\\test.xml");

string result = (string)doc.Root.Element("Ambassador");

LINQ-to-XML is much more friendly than the Xml* classes (System.Xml).


Otherwise you should be able to get the value of the element by retrieving the InnerText property.

string result = x.InnerText;
like image 96
dtb Avatar answered Sep 19 '22 13:09

dtb