请考虑以下事项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>
Run Code Online (Sandbox Code Playgroud)
我想选择Value的节点Item具有Code节点与价值MyCode.我该如何使用XPath?
我尝试过使用Items/Item[Code=MyCode]/Value它似乎没有用.
您的XML数据是错误的.该Value标签没有正确匹配关闭标签,你的Item标记没有匹配的结束标记(</Item>).
至于XPath,请尝试用引号括起要匹配的数据:
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);
Run Code Online (Sandbox Code Playgroud)