1

最近、JSoup を使用して HTML ドキュメントを解析および変更するように勧められました。

しかし、変更したい HTML ドキュメントがある場合 (送信、別の場所に保存するなど)、元のドキュメントを変更せずにそれを行うにはどうすればよいでしょうか?

次のような HTML ファイルがあるとします。

<html>
 <head></head>
 <body>     
  <p></p>
  <h2>Title: title</h2>
  <p></p>
  <p>Name: </p>
  <p>Address: </p>
  <p>Phone Number: </p>
 </body>
</html>

また、元の HTML ファイルを変更せずに、名前、住所、電話番号、その他の必要な情報を適切に入力したいのですが、JSoup を使用してどのようにすればよいでしょうか?

4

2 に答える 2

0

@MarcoS は、NodeTraversor を使用してhttps://stackoverflow.com/a/6594828/1861357で変更するノードのリストを作成する優れたソリューションを持っていました。ノード (タグのセット) をノード内のデータと追加したい情報。

文字列をメモリに保存するために、静的を使用しStringBuilderて HTML をメモリに保存しました。

最初に HTML ファイル (手動で指定され、変更可能) を読み込み、一連のチェックを行って、必要なデータを持つノードを変更します。

MarcoS による解決策で私が修正しなかった問題の 1 つは、行を見るのではなく、個々の単語を分割することでした。ただし、複数の単語に「-」を使用しただけです。そうしないと、その単語の直後に文字列が配置されるためです。

したがって、完全な実装:

import java.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
import java.io.*;

public class memoryHTML
{
    static String htmlLocation = "C:\\Users\\User\\";               
    static String fileName = "blah";                            // Just for demonstration, easily modified.
    static StringBuilder buildTmpHTML = new StringBuilder();
    static StringBuilder buildHTML = new StringBuilder();
    static String name = "John Doe";
    static String address = "42 University Dr., Somewhere, Someplace";
    static String phoneNumber = "(123) 456-7890";

    public static void main(String[] args)
    {
        // You can send it the full path with the filename. I split them up because I used this for multiple files.
        readHTML(htmlLocation, fileName);
        modifyHTML();

        System.out.println(buildHTML.toString());

        // You need to clear the StringBuilder Object or it will remain in memory and build on each run.
        buildTmpHTML.setLength(0);
        buildHTML.setLength(0);

        System.exit(0);
    }

    // Simply parse and build a StringBuilder for a temporary HTML file that will be modified in modifyHTML()
    public static void readHTML(String directory, String fileName)
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(directory + fileName + ".html"));

            String line;
            while((line = br.readLine()) != null)
            {
                buildTmpHTML.append(line);
            }
            br.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.exit(1);
        }
    }

    // Excellent method of parsing and modifying nodes in HTML files by @MarcoS at https://stackoverflow.com/a/6594828/1861357
    // It has its small problems, but it does the trick.
    public static void modifyHTML()
    {
        String htmld = buildTmpHTML.toString();
        Document doc = Jsoup.parse(htmld);

        final List<TextNode> nodesToChange = new ArrayList<TextNode>();

        NodeTraversor nd  = new NodeTraversor(new NodeVisitor() 
        {
          @Override
          public void tail(Node node, int depth) 
          {
            if (node instanceof TextNode) 
            {
              TextNode textNode = (TextNode) node;
              nodesToChange.add(textNode);
            }
          }

          @Override
          public void head(Node node, int depth) 
          {        
          }
        });

        nd.traverse(doc.body());

        for (TextNode textNode : nodesToChange) 
        {
          Node newNode = buildElementForText(textNode);
          textNode.replaceWith(newNode);
        }

        buildHTML.append(doc.html());
    }

    private static Node buildElementForText(TextNode textNode) 
      {
        String text = textNode.getWholeText();
        String[] words = text.trim().split(" ");
        Set<String> units = new HashSet<String>();
        for (String word : words) 
            units.add(word);

        String newText = text;
        for (String rpl : units) 
        {
            if(rpl.contains("Name"))
                newText = newText.replaceAll(rpl, "" + rpl + " " + name:));
            if(rpl.contains("Address") || rpl.contains("Residence"))
                newText = newText.replaceAll(rpl, "" + rpl + " " + address);
            if(rpl.contains("Phone-Number") || rpl.contains("PhoneNumber"))
                newText = newText.replaceAll(rpl, "" + rpl + " " + phoneNumber);
        }
        return new DataNode(newText, textNode.baseUri());
      }

そして、この HTML が返されます (「電話番号」を「電話番号」に変更したことを思い出してください):

<html>
 <head></head>
 <body>     
  <p></p>
  <h2>Title: title</h2>
  <p></p>
  <p>Name: John Doe </p>
  <p>Address: 42 University Dr., Somewhere, Someplace</p>
  <p>Phone-Number: (123) 456-7890</p>
 </body>
</html>
于 2013-09-19T23:47:18.253 に答える