如何为xpath-seach设置上下文

本文关键字:设置 上下文 xpath-seach | 更新日期: 2023-09-27 18:28:41

我有一个到服务器的ajax请求,该请求返回如下所示的html页面:''

<div class="item">
    <div class="name">
        <b>Name of the item</b>
    </div>
    <div class="itemProp">
        <input type="hidden" name="index" value="88">
    </div>
</div>

这种情况持续下去,因为有很多项目符合我的要求。现在我希望能够获得项目的名称和索引值。

我所做的是:

var itemCollection = doc.DocumentNode.SelectNodes("div[@class ='item']");
foreach (var item in itemCollection)
{
    Console.WriteLine("Name {0}",item.SelectSingleNode("//b").InnerText);
    Console.WriteLine("rdef index {0}", item.SelectSingleNode("//input[@name='index']").GetAttributeValue("value","Not Found"));
}

但我在整个文档中搜索标签,所以每次只返回第一个。

我的问题是,我如何使用Xpath和HtmlAgilityPack设置要搜索的上下文,这样当我进入for循环时,它只搜索项目子项中的b标记,而不是整个文档。此外,如果有更好的方法可以做到这一点,我愿意接受建议!

如何为xpath-seach设置上下文

使用.//foo:

Console.WriteLine("Name {0}",item.SelectSingleNode(".//b").InnerText);

对于其他相对路径也是如此,例如

Console.WriteLine("rdef index {0}", item.SelectSingleNode(".//input[@name='index']").GetAttributeValue("value","Not Found"));

您可以使用XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication63
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<?xml version='"1.0'" encoding='"utf-8'" ?>" +
                "<Root>" +
                  "<div class='"item'">" +
                    "<div class='"name'">" +
                      "<b>Name of the item</b>" +
                    "</div>" +
                    "<div class='"itemProp'">" +
                      "<input type='"hidden'" name='"index'" value='"88'"/>" +
                    "</div>" +
                  "</div>" +
                  "<div class='"item'">" +
                    "<div class='"name'">" +
                      "<b>Name of the item</b>" +
                    "</div>" +
                    "<div class='"itemProp'">" +
                      "<input type='"hidden'" name='"index'" value='"88'"/>" +
                    "</div>" +
                  "</div>" +
                "</Root>";
            XDocument doc = XDocument.Parse(xml);
            var results = doc.Descendants().Where(x => (x.Name.LocalName == "div") && (x.Attribute("class") != null) && x.Attribute("class").Value == "item").Select(y => new {
                name = y.Descendants("b").FirstOrDefault().Value,
                value = y.Descendants("input").FirstOrDefault().Attribute("value").Value
            }).ToList();
        }
    }
}