簡體   English   中英

使用Java解析HTML標簽

[英]Parsing HTML tags using Java

我試圖創建一個HTML解析器來檢查HTML標記並驗證是否有一個與每個打開標記相對應的結束標記。

我現在所擁有的部分工作,我相信邏輯是正確的,但是我在使令牌正確方面遇到問題。 當我運行我擁有的代碼時,它需要很多空令牌,將其與其他非空令牌進行比較顯然會產生錯誤。

我想知道如何從HTML文件中讀取它,但只能將內容放入<和>之間的標記中。 我也不希望任何額外的數據,例如將h1標記之間的文本考慮在內。

這是用於學校作業,我相信教授希望我們不使用JTidy這樣的第三方計划就可以做到這一點。

任何幫助是極大的贊賞。

import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;


public class HTMLDriver
{
   public static void main(String [] args) throws IOException
   {
     // declare variables
     QueueReferenceBased queue = new QueueReferenceBased();

     // Create a scanner object 

     Scanner in = new Scanner(System.in);
     System.out.println("What is your html file name?");
     String fileName = in.next();

     File userFile = new File(fileName);

     if (!userFile.exists())
     {
        System.out.println("File does not exist. This program will now exit.");
        System.exit(0);
     }

    Scanner inputFile = new Scanner(userFile); 
    while (inputFile.hasNext())
    {

        String str = inputFile.nextLine();
        StringTokenizer st = new StringTokenizer(str,"<>");

       //Adds tokens to queue
       while(st.hasMoreTokens())
       {
       String token = st.nextToken();
       Tag t = new Tag(token);
       queue.enqueue(t);
      }
    }   
    //Creates Stack
    StackReferenceBased stack = new StackReferenceBased();

    //Loops through queue if not empty
    while(!queue.isEmpty())
    {
      Object obj = queue.dequeue();
      Tag t2 = (Tag)obj;

        if(t2.getOpen() == true)
        {
           stack.push(t2);
        }

        if(t2.getOpen() == false)
        {
           if(stack.isEmpty())
           {
              System.out.println("There is no match for the " + t2 + " tag");
           }else
           {
              Object obj2 = stack.pop();
              Tag t3 = (Tag)obj2;

              //Make tag class and check equality

              if(t2.getTag().equals(t3.getTag()))
              {
                 System.out.println(t2 + " matches " + t3);
              }else
              {
                 System.out.println("Found " + t2 + " to match " + t3 + " terminating program");
                 System.exit(0);
              }

           }
        }
    }    
  }   
}

不要這樣 HTML在這方面是臭名昭著的。 有些標簽沒有打開/關閉<>的功能-那么就存在所有格式錯誤的HTML,並且瀏覽器有些古怪。

除非您的教授明確地禁止您使用第三方庫,否則嘗試以健壯的規模嘗試是不明智的。 在XML上,這是可管理的。

如果您確實必須單獨執行此操作,則可以使用正則表達式獲得不錯的結果

Pattern p = Pattern.compile("<(.*)>") // will get your started. you can then do:

Matcher m = p.matcher();
m.group( ... ) // this will get you everything between parentheses in the regex 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM