[英]HTML Well-formedness parser
大家好,我需要確定給定的HTML文檔格式是否正確。
我只需要一個僅使用Java核心API類的簡單實現即可,即不需要第三方的東西(如JTIDY等)。
實際上,真正需要的是一種掃描TAGS列表的算法。 如果找到打開的標簽,而下一個標簽不是其對應的關閉標簽,則它應該是另一個打開標簽,而該標簽又應將其關閉標簽作為下一個標簽,如果不是,則應該是另一個打開標簽,然后其對應的關閉標簽下一個,以及先前打開標簽的關閉標簽以相反的順序在列表中一個接一個地排列。 如果列表符合此順序,則返回true或false。 我已經寫了將標簽轉換為關閉標簽的方法。
這是我已經開始從事的工作的基本代碼。 它不是太整潔,但是它應該使你們對我正在嘗試做的事情有一個基本的了解。
public boolean validateHtml(){
ArrayList<String> tags = fetchTags();
//fetchTags returns this [<html>, <head>, <title>, </title>, </head>, <body>, <h1>, </h1>, </body>, </html>]
//I create another ArrayList to store tags that I haven't found its corresponding close tag yet
ArrayList<String> unclosedTags = new ArrayList<String>();
String temp;
for (int i = 0; i < tags.size(); i++) {
temp = tags.get(i);
if(!tags.get(i+1).equals(TagOperations.convertToCloseTag(tags.get(i)))){
unclosedTags.add(tags.get(i));
if(){
}
}else{
return true;//well formed html
}
}
return true;
}
兩個想法。 首先,也許您可以在html上使用XML解析器? 可能更容易,而且大大節省時間。
我對此並沒有考慮太多,但對我來說,聽起來像是遞歸和堆棧是要走的路。 就像是
public myClass(String htmlInput)
{
openedTags = new Stack<String>();
this.htmlInput = htmlInput;
}
public boolean validate()
{
return validate(this.htmlInput);
}
private boolean validate(String html)
{
boolean result = true;
String curTag;
while(htmlLeft) //worker loop
{
if(isOneOffTag(curTag)) //matches <tags />
continue;
else if(isOpenTag(curTag)) //matches <tags>
{
openedTags.push(curTag);
if(!validate(innerHtml))
return false;
}
else if(isCloseTag(curTag)) //matches </tags>
{
String lastTag = (String)openedTags.peek();
if(!tagIsSimiliar(curTag, lastTag))
return false;
openedTags.pop();
}
}
return result;
}
private String nextTag(){return null;}
private boolean isOpenTag(String tag){ return true;}
private boolean isCloseTag(String tag){ return true;}
private boolean isOneOffTag(String tag){ return true;}
private boolean tagIsSimiliar(String curTag, String lastTag){return true;}
* edit 1:可能應該已經壓入堆棧。
** edit 2:我想這里的問題是確定僅返回布爾值時您在哪里遺漏了。 這將需要某種指針,這樣您才能知道您離開的地方。 盡管我相信這個想法仍然可以奏效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.