Florin M.
Florin M.

Reputation: 2169

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?

Upvotes: 1

Views: 378

Answers (1)

NtFreX
NtFreX

Reputation: 11377

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.

Upvotes: 2

Related Questions