Jsoup 解析 html-string

Jsoup parse html-string

我有这个Element:

<td id="color" align="center">
Z 29.02-23.05 someText,
<br> 
some.Text2 <a href="man.php?id=111">J. Smith</a> (l.)&nbsp;
</td>

如何让标签 <br> 后的文本看起来像 some.Text2 J. Smith 我试图在文档中找到答案,但是...

更新

如果我使用

System.out.println(element.select("a").text());

我只得到 J。史密斯。不幸的是,我不知道如何解析像 <br>

这样的标签

据我所知,您只能接收两个标签之间的文本,这对于文档中的单个 <br/> 标签是不可能的。

我能想到的唯一选择是使用 split() 来接收第二部分:

String partAfterBr = element.text().split("<br>")[1];
Document relevantPart = JSoup.parse(partAfterBr);
// do whatever you want with the Document in order to receive the necessary parts

Node.childNodes 可以挽救你的生命:

package com.github.davidepastore.Whosebug35436825;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

/**
 * Whosebug 35436825
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        String html = "<html><body><table><tr><td id=\"color\" align=\"center\">" +
                        "Z 29.02-23.05 someText," +
                        "<br>" +
                        "some.Text2 <a href=\"man.php?id=111\">J. Smith</a> (l.)&nbsp;" +
                        "</td></tr></table></body></html>";
        Document doc = Jsoup.parse( html );
        Element td = doc.getElementById( "color" );
        String text = getText( td );
        System.out.println("Text: " + text);
    }

    /**
     * Get the custom text from the given {@link Element}.
     * @param element The {@link Element} from which get the custom text.
     * @return Returns the custom text.
     */
    private static String getText(Element element) {
        String working = "";
        List<Node> childNodes = element.childNodes();
        boolean brFound = false;
        for (int i = 0; i < childNodes.size(); i++) {
            Node child = childNodes.get( i );
             if (child instanceof TextNode) {
                 if(brFound){
                     working += ((TextNode) child).text();
                 }
             }
             if (child instanceof Element) {
                 Element childElement = (Element)child;
                 if(brFound){
                     working += childElement.text();
                 }
                 if(childElement.tagName().equals( "br" )){
                     brFound = true;
                 }
             }
        }
        return working;
    }
}

输出将是:

Text: some.Text2 J. Smith (l.)