简体   繁体   中英

How to filter noise in nested tags in JSoup? java

How to filter noise in nested tags? For example, i have this input:

[in:]

<html>
  <source>
     <noise>something something, many many things</noise>foo bar bar<noise>more something something noise</noise>baring foo
  </source>
</html>

and i need to get this output:

[out]

foo bar bar
baring foo

I have tried this but I am still getting the noise from the nested tags:

import java.io.*;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;

public class HelloJsoup {
    public static void main(String[] args) throws IOException {

        String br = "<html><source><noise>something something, many many things</noise>foo bar bar<noise>more something something noise</noise>baring foo</source></html>";
        Document doc = Jsoup.parse(br, "", Parser.xmlParser());
        //System.out.println(doc);
        for (Element sentence : doc.getElementsByTag("source"))
            System.out.print(sentence.text());

    }
}

[out:]

something something, many many thingsfoo bar barmore something something noisebaring foo

By removing the noise tags first, you are left with <source>foo bar barbaring foo</source> , though to achieve the output you specified, you can just iterate through the nodes and print each TextNode on a new line. For example:

String br = "<html><source><noise>something something, many many things</noise>foo bar bar<noise>more something something noise</noise>baring foo</source></html>";
Document doc = Jsoup.parse(br, "", Parser.xmlParser());

Element source = doc.select("source").first(); // select source element

Elements noise = doc.select("noise");          // Select noise elements
for (Element e : noise) {                      // loop through and remove each from doc
    e.remove();
}

for (Node node : source.childNodes()) {
    System.out.println(node);                  // print each remaining textnode on a new line
}

Outputs:

foo bar bar
baring foo

Update

I found this to be an even simpler method:

Element source = doc.select("source").first(); // select source element

for (TextNode node : source.textNodes()) {
    System.out.println(node);
}

It iterates through the textNodes owned directly by the <source> element and prints each one to a new line. Ouput is:

foo bar bar
baring foo

尝试:

System.out.println(sentence.ownText());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM