[英]How can I determine if a HTML document is well formed or not in JAVA?
大家好,我需要確定給定的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復制到數組中
bool tag = false;
string str = "";
List<string> htmlTags = new List();
for(int i = 0; i < array.length; i++)
{
//Check for the start of a tag
if(array[i] == '<')
{
tag == true;
}
//If the current char is part of a tag start copying
if(tag)
{
str += char;
}
//When a tag ends add the tag to your tag list
if(array[i] == '>')
{
htmlTags.Add(str);
str = "";
tag == false;
}
}
像這樣的東西應該讓您開始,您應該最終得到一個標簽數組,這只是偽代碼,所以它不應該編譯
不要認為您可以在不進行大量工作的情況下做到這一點,使用第三方軟件包會容易得多
嘗試針對HTML4或4.1或XHTML 1 DTD進行驗證
"strict.dtd"
"loose.dtd"
"frameset.dtd"
這可能有幫助!
也許您可以根據需要調整此示例 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.