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.

5
  • 1
    Try setting MyCode in astring like this "MyCode", and if it is possible I would recommend using Linq-to-XML. Commented Jun 1, 2011 at 15:29
  • This "XML" is a mess - now well-formed! Commented Jun 1, 2011 at 15:33
  • @alexbrn: The bad XML may well be part of the problem, so should be in the answer (in this case). I've addressed it in my answer, for example. I suggest leaving the question how it was asked. Commented Jun 1, 2011 at 15:36
  • Changed the XML. My XML is a little bit more complex :P. Was just a typo. Commented Jun 1, 2011 at 15:37
  • Sorry about that. Please edit again, and I won't "fix" the changes :) Make sure you take care of the Value end tags too - right now they're Code end tags. Commented Jun 1, 2011 at 15:39

2 Answers 2

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

2 Comments

It seems that the quotes are the issue.
Yes, without the quotes it tries to compare the value of the node Code, to the value of the node MyCode. As expected it doesn't find a node called MyCode.
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>

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.