问题描述
我有这个 XML 片段
<unit class="xxx.xxx.xxx" id="382">
<customId>000</customId>
<description>kg</description>
<key>22452</key>
<Description>Kilogramm</Description>
</unit>
如何使用元素的值获取关键元素的节点“单元”或parnet。例如
我在 [22452] 上面有关键元素的值,它是 xml 文件中的 Uniqe。
我正在尝试获取该特定标签的 customid [000] 的值。
我做了什么:
var doc = new XmlDocument();
doc.Load(stream); // stream from xml-file
var key = doc.SelectSingleNode(//key/[text()='" + 22452+ "']"); // that i am not sure about it.
var customId = key.InnerText("customId");
解决方法
对于这种查询,您可以找到节点,然后导航到父节点。
或者使用 XPath:
var unitElemnt = doc.SelectSingleNode("//unit[key = '22452']");
(假设我记得 XPath 以正确匹配元素的文本内容。)
这通过在 XPath 表达式的谓词中使用 <unit>
元素的相对路径,获取对 <key>
元素的引用。
通常最好避免在 XPath 中使用 //
以提高性能,但需要完整的文档结构才能做到这一点。
为此,您可以使用 Linq to Xml 查询。
XElement units = XElement.Load("./Test.xml");
XElement unit = (from item in units.Descendants("unit")
where item.Element("key").Value == "22455"
select item).FirstOrDefault();
string customId = unit.Element("customId").Value;
假设您的 xml 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<units>
<unit class="xxx.xxx.xxx" id="385">
<customId>003</customId>
<description>kg</description>
<key>22455</key>
<Description>Kilogramm</Description>
</unit>
<unit class="xxx.xxx.xxx" id="386">
<customId>004</customId>
<description>kg</description>
<key>22456</key>
<Description>Kilogramm</Description>
</unit>
</units>