【问题标题】:Java Html Parser and Closing TagsJava Html 解析器和关闭标记
【发布时间】:2010-04-27 03:34:50
【问题描述】:

如何使用 Java HTML 解析器库处理结束标记(例如:</h1>)?

例如,如果我有以下情况:

public class MyFilter implements NodeFilter {

 public boolean accept(Node node) {
  if (node instanceof TagNode) {
   TagNode theNode = (TagNode) node;
   if (theNode.getRawTagName().equals("h1")) {
    return true;
   } else {
    return false;
   }
  }
  return false;
 }
}

public class MyParser {
 public final String parseString(String input) {
  Parser parser = new Parser();
  MyFilter theFilter = new MyFilter();
  parser.setInputHTML("<h1>Welcome, User</h1>");
  NodeList theList = parser.parse(theFilter);
  return theList.toHtml();
 }
}

当我运行解析器时,我得到以下输出:

<h1>Welcome, User</h1>Welcome, User</h1>

NodeList 包含一个大小为 3 的列表,其中包含以下实体:

(tagNode) <h1>

(textNode) Welcome, User

(tagNode) </h1>

我希望输出为“&lt;h1&gt;Welcome, User&lt;/h1&gt;”。有人看到我的示例解析器有什么问题吗?

【问题讨论】:

    标签: java html parsing


    【解决方案1】:

    提示:

    我认为在这种情况下你必须依赖isEndTag() API。

    【讨论】:

      【解决方案2】:

      您的过滤器接受的节点过多。对于您的示例输入,您希望为&lt;h1&gt; 标记创建一个只有一个节点的NodeList。其他两个节点是第一个节点的子节点,因此不应添加到 NodeList


      如果您添加以下代码,您可能会更好地看到问题所在。

      for (Node node : theList.toNodeArray())
      {
          System.out.println(node.toHtml());
      }
      

      应该打印出来

      <h1>Welcome, User</h1>
      Welcome, User
      </h1>
      

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 2012-05-25
        • 1970-01-01
        • 2010-12-26
        • 2011-01-08
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        • 2010-10-25
        相关资源
        最近更新 更多