Shawn
Shawn

Reputation: 2366

Select XML Element based on another elements value

<Root>
    <Sub>
        <Name>a</Name>
        <Value>1</Value>
    </Sub>
    <Sub>
        <Name>b</Name>
        <Value>2</Value>
    </Sub>
</Root>

How do I select the value of the Value element dependent upon the Name element?

Edit: In an XDocument, how do I get the value "1" when I have "a".

Upvotes: 1

Views: 3000

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

I suggest you to use casting nodes instead of accessing Value property directly:

int value = xdoc.Descendants("Sub")
                .Where(s => (string)s.Element("Name") == "a")
                .Select(s => (int)s.Element("Value"))
                .FirstOrDefault();

If default value (zero) for missing nodes does not fit your needs, then you can check required Sub element exists before getting value:

var sub = xdoc.Descendants("Sub")
              .FirstOrDefault(s => (string)s.Element("Name") == "a");

if (sub != null)            
    value = (int)sub.Element("Value");

Or simple one line with XPath and Linq:

int value = (int)xdoc.XPathSelectElement("//Sub[Name='a']/Value");

Upvotes: 2

JLRishe
JLRishe

Reputation: 101758

This should do it:

(assuming doc is an instance of XDocument)

string name = "a";
var items = doc.Descendants("Sub")
               .Where(s => (string)s.Element("Name") == name)
               .Select(s => s.Element("Value").Value);

items would result as an IEnumerable<string> in this case.

If you know you only want one value:

string name = "a";
string value = doc.Descendants("Sub")
               .Where(s => (string)s.Element("Name") == name)
               .Select(s => s.Element("Value").Value)
               .FirstOrDefault();

Upvotes: 1

dotmido
dotmido

Reputation: 1384

you may try this, may help

var results = from row in xdoc.Root.Descendants("Sub")
where row.Element("Name").value ="value"
select new XElement("row", row.Element("Value"));

Upvotes: 1

Sagar Upadhyay
Sagar Upadhyay

Reputation: 819

Well, think about it...

you can easily read XML file, just you have to check the condition if the inner text of <Name> is match with your condition than you have to read the value of <value> tag.

Here is you can get answer for how to read XML file from c# code.

Upvotes: 1

Related Questions