【问题标题】:select childenode from collection htmlagilitypack从集合 htmlagilitypack 中选择子节点
【发布时间】:2012-07-02 04:37:42
【问题描述】:

我有这个 hap 代码,它试图从节点的主集合中选择子节点

Dim items As HtmlNodeCollection = doc.DocumentNode.SelectNodes("//channel/item")

 For Each item In items
   link = item.SelectSingleNode("//link")
   title = item.SelectSingleNode("//title")
 next

xml 是

<rss version="2.0">
<channel>
    <title>title title</title>
<link>http://www.link.com</link>
<description>long decription</description>
<item>
    <title>title title</title>
    <link>http://www.link.com/</link>
    <description> description</description>
    </item>
    <item>
    <title>title title</title>
    <link>http://www.link.com/</link>
    <description> description</description>
    </item>
    <item>
    <title>title title</title>
    <link>http://www.link.com/</link>
    <description> description</description>
    </item>
</channel>
</rss>

但我没有得到每个项目的相应节点标题和项目下的链接。 我哪里弄错了?

我本来可以做的

Dim links As HtmlNodeCollection = doc.DocumentNode.SelectNodes("//channel/item/link")
Dim titles As HtmlNodeCollection = doc.DocumentNode.SelectNodes("//channel/item/title")

但我需要每个项目的链接和标题

【问题讨论】:

  • 为什么不在您的帖子中包含一些 HTML,以便我们查看您查询的内容?
  • @SteveWellens 我更新了我的问题,感谢您的回复
  • 您的示例中的item 标签是否未关闭?
  • @thecoon 他们是,这是一个拼写错误,谢谢。我纠正了它

标签: .net html-parsing html-agility-pack


【解决方案1】:

在我看来,这就像 HtmlAgilityPack 中的一个错误。我只为link 元素检索InnerText 时遇到问题,而不是其他元素。对于那个,文本被发现是它的兄弟,至少不是孩子。

无论如何,这不会是 HtmlAgilityPack 中遇到的第一个错误,所以我们应该忍受它:)。

替代方案:

使用XmlDocument,因为这里不涉及 HTML。那是一个 XML。

static void Main(string[] args)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(ConsoleApplication3.Properties.Settings.Default.RSS);

    var items = xmlDoc.SelectNodes("//channel/item");
    foreach (var item in items)
    {
        XmlNode node = (XmlNode)item;
        var link = node.SelectSingleNode("//link");
        var title = node.SelectSingleNode("//title");

        if (link != null)
        {
            Console.WriteLine(link.InnerText);
        }
        if (title != null)
        {
            Console.WriteLine(title.InnerText);
        }
    }

    Console.ReadKey();
}

输出:

http://www.link.com

标题标题

http://www.link.com

标题标题

http://www.link.com

标题标题

【讨论】:

  • 请再看一下xml,ithin item是直系后代
猜你喜欢
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多