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>开发者_Go百科;
<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.
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);
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>
精彩评论