简体   繁体   中英

Get content of XML node using c#

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?

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;

The InnerText property should work fine for you.

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.innertext.aspx

FWIW, you might consider switching API to linq-to-xml (XElement and friends) as IMHO it's a friendly, easier API to interact with.

System.Xml version (NOTE: no casting to XmlElement needed)

var xml = @"<TimelineInfo>
                <PreTrialEd>Not Started</PreTrialEd>
                <Ambassador>Problem</Ambassador>
                <PsychEval>Completed</PsychEval>
            </TimelineInfo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.SelectSingleNode("/TimelineInfo/Ambassador");
Console.WriteLine(node.InnerText);

linq-to-xml version:

var xml = @"<TimelineInfo>
                <PreTrialEd>Not Started</PreTrialEd>
                <Ambassador>Problem</Ambassador>
                <PsychEval>Completed</PsychEval>
            </TimelineInfo>";
var root = XElement.Parse(xml);
string ambassador = (string)root.Element("Ambassador");
Console.WriteLine(ambassador);
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");

x.InnerText will return the contents

尝试使用Linq to XML - 它提供了一种查询xml数据源的简单方法 - http://msdn.microsoft.com/en-us/library/bb387098%28v=VS.100%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM