1
<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".

Shawn
  • 2,356
  • 6
  • 48
  • 82

4 Answers4

2

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");
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

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.

Community
  • 1
  • 1
Sagar Upadhyay
  • 819
  • 2
  • 11
  • 31
1

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"));
dotmido
  • 1,374
  • 3
  • 13
  • 29
1

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();
JLRishe
  • 99,490
  • 19
  • 131
  • 169