Florin M. Florin M. - 9 days ago 6
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>
</profile>
</information>


I do want to take the value of the element
<name>
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

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.