fuller
fuller

Reputation: 41

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);

Upvotes: 0

Views: 277

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

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']");

Upvotes: 1

Related Questions