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

1
  • 1
    What exactly do you mean? Commented Mar 11, 2013 at 18:51

4 Answers 4

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Marked as answer since I completely forgot about XPath and should've just used that.
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.

Comments

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"));

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.