如何根据XPath中的条件查找两个元素中的文本?

时间:2013-02-08 13:27:13

标签: xml xpath

这是我的XML

<?xml version="1.0" encoding="ISO8859-1" ?>
<!-- modified from http://www.xmlfiles.com/examples/simple.xml -->
<_breakfastmenu>
<food type="vegetarian">
  <name>Belgian Waffles</name>
  <price>5.95</price>
  <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
  <calories>650</calories>
</food>
<food type="vegetarian">
  <name>Strawberry Belgian Waffles</name>
  <price>7.95</price>
  <description>light Belgian waffles covered with strawberries and whipped cream</description>
  <calories>900</calories>
</food>
<food type="vegetarian">
  <name>Berry-Berry Belgian Waffles</name>
  <price>8.95</price>
  <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
  <calories>900</calories>
</food>
<food type="vegetarian">
  <name>French Toast</name>
  <price>4.50 </price>
  <description>thick slices made from our homemade sourdough bread</description>
  <calories>600</calories>
</food>

</_breakfastmenu>

我想找到包含“Waffles”的所有食物元素,我可以通过运行此XPath成功完成此任务:

_breakfastmenu/food/name[contains(text(), "Waffles")] 

但是我想找出这些的价格,这样做的正确方法是什么,我尝试了一段时间没有成功,任何帮助都表示赞赏。

谢谢。

2 个答案:

答案 0 :(得分:2)

XPath表达式

/_breakfastmenu/food[contains(name, 'Waffles')]/price

会提取您感兴趣的元素。通常不需要使用text(),因为元素节点的字符串值是其所有后代文本节点的串联。如果您正在查看的元素可能包含子元素或多个文本节点,例如

<foo>This is a <i>contrived</i> example</foo>

然后foo元素的字符串值是“这是一个人为的例子”,而foo/text()会给你两个文本节点,“这是一个”和“示例”。根据您使用此节点集的上下文,您最终可能会迭代节点或仅使用第一个节点的值(“This is a”)。如果您不确定是否需要text(),那么您可能不需要。{/ p>

答案 1 :(得分:0)

我不是这方面的专家,但这会吗?

XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("http://localhost:49288/EktronSite2/XMLFiles/Food.xml");//ur xml location
        XmlNodeList nodes = xmlDoc.SelectNodes("_breakfastmenu/food");
        if(nodes != null)
        {
            foreach (XmlNode node in nodes)
            {
                if (node.SelectSingleNode("name").InnerText.Contains("Waffles"))
                {
                    Response.Write(node.SelectSingleNode("name").InnerText+ ":" +node.SelectSingleNode("price").InnerText + "<br><br>");
                }
            }
        }