0

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

1 Answer 1

1
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']");
Sign up to request clarification or add additional context in comments.

3 Comments

What if the doc tag is a descendent of another xml. using (string)docs.descendent("doc").XPathSelectElement("//str[@name='stage4']"); seems not working
@user3083435 you can use Descendtants (which looks all descendant elements in file) instead of Elements (which looks only direct children). Or you can specify full path like Root.Element("doc").Elemtents("str")
Thank for your advise. Good to know there are so many ways to parse an xml.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.