我需要通過屬性值的模式搜索 XML 元素。我當前正在處理的 XML 文件如下所示:<root> <items> <item Id=“001” name=“Foo001”></item> <item Id=“002” name=“Foo002”></item> <item Id=“003” name=“Boo001”></item> </items></root>我需要搜索 name 屬性值以“Boo”開頭的元素我嘗試使用以下代碼(在谷歌上找到)進行搜索,但它不起作用XmlDocument doc = new XmlDocument();doc.Load(myXmlFilePath);XmlNode match = doc.SelectSingleNode(“/root/items/item[substring(@name,1,3)=‘Boo’]”);Console.WriteLine(match.Value.ToString());誰能告訴我如何用 C# 實現我需要的東西?
1 回答

小唯快跑啊
TA貢獻1863條經驗 獲得超2個贊
您在 XML 和 XPATH 中使用了錯誤的引號。
將 XML 中的“更改為””
將 XPATH 中的 'to' 更改為
<root>
<items>
<item Id="001" name="Foo001"></item>
<item Id="002" name="Foo002"></item>
<item Id="003" name="Boo001"></item>
</items>
</root>
XmlNode match = doc.SelectSingleNode("/root/items/item[substring(@name,1,3)='Boo']");
為了讀取結果:
// read the attribute name
Console.WriteLine(match.Attributes["name"].Value);
// read the text in item
Console.WriteLine(match.InnerText);
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消