[英]Java Html Parser and Closing Tags
如何使用Java HTML Parser Library处理结束标记(例如: </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>
我希望输出为“ <h1>Welcome, User</h1>
”。 有人在我的示例解析器中看到什么地方出问题了吗?
暗示:
我认为在这种情况下,您必须依赖isEndTag() API。
您的过滤器接受了太多的节点。 对于您的示例输入,您想为<h1>
标签创建一个只有一个节点的NodeList
。 其他两个节点是第一个节点的子节点,因此不应将其添加到NodeList
。
如果添加以下代码,则可能会更好地了解问题所在。
for (Node node : theList.toNodeArray())
{
System.out.println(node.toHtml());
}
它应该打印
<h1>Welcome, User</h1>
Welcome, User
</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.