[英]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.