XPath: choose a node based on another node?

Consider the following XML:

<Items>
    <Item>
        <Code>Test</Code>
        <Value>Test</Value>
    </Item>
    <Item>
        <Code>MyCode</Code>
        <Value>MyValue</Value>
    </Item>
    <Item>
        <Code>AnotherItem</Code>
        <Value>Another value</Value>
    </Item>
</Items>

I would like to select a Valuenode Itemthat has a Codenode in with a value MyCode. How can i use XPath?

I tried using Items/Item[Code=MyCode]/Value, but it does not work.

+3
source share
2 answers

The XML data is invalid. A tag Valuedoes not have valid matching closing tags, and tags Itemdo not have matching closing tags ( </Item>).

As for your XPath, try including the data you want to match in quotes:

const string xmlString =
@"<Items>
    <Item>
        <Code>Test</Code>
        <Value>Test</Value>
    </Item>
    <Item>
        <Code>MyCode</Code>
        <Value>MyValue</Value>
    </Item>
    <Item>
        <Code>AnotherItem</Code>
        <Value>Another value</Value>
    </Item>
</Items>";

var doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlElement element = (XmlElement)doc.SelectSingleNode("Items/Item[Code='MyCode']/Value");
Console.WriteLine(element.InnerText);
+7
source

You need:

/ Items / Item [Code = "MyCode"] / Value

, XML:

<?xml version="1.0"?>
<Items>
  <Item>
    <Code>Test</Code>
    <Value>Test</Value>
  </Item>
  <Item>
    <Code>MyCode</Code>
    <Value>MyValue</Value>
  </Item>
  <Item>
    <Code>AnotherItem</Code>
    <Value>Another value</Value>
  </Item>
</Items>
+1

All Articles