如何通过属性值的模式查找XML元素

我需要通过属性值的模式搜索 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# 实现我需要的东西?


MMMHUHU
浏览 52回答 1
1回答

小唯快跑啊

您在 XML 和 XPATH 中使用了错误的引号。将 XML 中的“更改为””将 XPATH 中的 'to' 更改为<root>&nbsp;<items>&nbsp; &nbsp; &nbsp;<item Id="001" name="Foo001"></item>&nbsp; &nbsp; &nbsp;<item Id="002" name="Foo002"></item>&nbsp; &nbsp; &nbsp;<item Id="003" name="Boo001"></item>&nbsp;</items></root>XmlNode match = doc.SelectSingleNode("/root/items/item[substring(@name,1,3)='Boo']");为了读取结果:// read the attribute nameConsole.WriteLine(match.Attributes["name"].Value);// read the text in item&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Console.WriteLine(match.InnerText);
打开App,查看更多内容
随时随地看视频慕课网APP