Florin M. Florin M. - 1 year ago 82
C# Question

get specific xelement child value

<information items ="2">
<table id="31"> </table>
<profile code="5">
<name language="ro"> Spania </name>
<name language="gb"> Spain </name>
<name language="pl"> Hiszpania </name>

I do want to take the value of the element
having its attribute
language = "gb"

I tried something like:

string country = xdoc.Descendants("information").Elements("profile").Elements("name")./*???Value???*?

How can I achieve this?

Answer Source

You can use XPath:

With System.Xml.Linq.XDocument:

string country = xdoc.XPathSelectElement("/information/profile/name[@language='gb']").Value;

With System.Xml.XmlDocument

string country = xdoc.SelectSingleNode("/information/profile/name[@language='gb']").InnerText;

Keep in mind that you also need the System.Xml.XPath namespace.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download