【问题标题】:get html node inner text segmented?获取 html 节点内部文本分段?
【发布时间】:2011-12-19 22:12:57
【问题描述】:

我正在尝试解析 html 页面,但我遇到了一个问题,即我想要分割节点的内部文本,即在 html 节点子节点上迭代,假设每个文本段都是子节点:

<node1>
This text I WANT on iterate#1
<innernode>This text I WANT on iterate#2</innernode>
This text I WANT on iterate#3
<innernode>This text I WANT on iterate#4</innernode>
This text I WANT on iterate#5
</node1>  

我正在使用htmlagilitypack 作为解析器,但我认为使用任何其他 html 解析器都会遇到这个问题

【问题讨论】:

  • 为什么不使用标准的 .net xml 类?

标签: c# .net xml html-parsing


【解决方案1】:

根据您的 .NET 版本,您可以使用适用于所需节点的扩展方法。 我没有使用过 html 敏捷包,所以这是 C# 和伪代码的混合。

例如

public static List<string> GetTextSegments(this HtmlNode node)
{
    string nodesText = ... // get the nodes text
    yield nodesText;

    List<HtmlNode> innerNodes = ... // get the list of inner nodes with a 
    // query like node.SelectNodes("//innerNodes")
    foreach(HtmlNode iNode in innerNodes)
    {
        string iNodeText = ... // get iNodes text
        yield iNodeText;
    }
}

你可以这样称呼它:

HtmlNode nodeOfTypeNode1 = ... // 
foreach(string text : nodeOfTypeNode1.getTextSegments())
{
    Console.WriteLine(text);
}

【讨论】:

    【解决方案2】:

    要实现您的目标,请将 SelectNodes 与 XPath 结合使用。

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(content);//content is the variable containing your html.
    var items = doc.DocumentNode.SelectNodes("/node1//text()");
    foreach (var item in items)
    {
        Console.WriteLine(item.OuterHtml.Replace("\r\n",""));
    }
    

    【讨论】:

    • 但是当我使用这种方式时,我无法处理 html 节点,我的意思是我无法获取节点的名称或其属性或其子节点
    • 您想要做的是获取所有文本,而不考虑内部文本和节点作为您的情况。如果是这样,DocumentNode.SelectNodes("//text()") 怎么样?
    猜你喜欢
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2012-06-02
    • 2015-12-07
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多