简体   繁体   中英

Parsing XML with multiple similar child nodes in C#

My response xml from webservice is like this:

<doc>
<str name="stage1">data1</str>
<date name="stage2">2013-08-23T09:25:12Z</date>
<str name="parent">data3</str>
<str name="stage4">xxx</str>

How to get the value of element stage4. My final output needs to be xxx. I have tried the following code:

Stream stream = r.GetResponse().GetResponseStream();
            XDocument docs = XDocument.Load(stream);

var data = docs.element(doc).element(stage4);
var data = (string)docs.Root.Elements("str")
               .FirstOrDefault(str => (string)str.Attribute("name") == "stage4");

Or with XPath

string data = (string)docs.XPathSelectElement("//str[@name='stage4']");

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