Java Html解析器和闭合标记

问题描述:

如何使用Java HTML解析器库处理闭合标记(例如:</h1>)?Java Html解析器和闭合标记

举例来说,如果我有以下几点:

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> 

节点列表包含大小3与第一个列表以下实体:

(tagNode) <h1> 

(textNode) Welcome, User 

(tagNode) </h1> 

我想输出为“<h1>Welcome, User</h1>”。有没有人看到我的示例解析器出了什么问题?

提示:

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

您的过滤器正在接受太多的节点。对于您的示例输入,您希望创建仅具有单个节点的NodeList - 对于<h1>标记。其他两个节点是该第一个节点的子节点,因此不应将其添加到NodeList


如果添加下面的代码,您可能会看到更好的问题。

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

应该打印

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