3

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 the Value node of the Item that has the Code node in with the value MyCode. How would I go about using XPath?

I've tried using Items/Item[Code=MyCode]/Value but it doesn't seem to work.

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203

2 Answers2

7

Your XML data is wrong. The Value tag doesn't have correct matching closing tags, and your Item tags don't have matching closing tags (</Item>).

As for your XPath, try enclosing 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);
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
1

You need:

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

Assuming you fix-up your 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>
alexbrn
  • 2,050
  • 13
  • 11