如何使用jsoup将当前元素嵌入到新元素中并更新到文档中

时间:2018-08-01 08:51:14

标签: java jsoup

我正在使用jsoup处理html,我想将元素嵌入到


来自:

<div>
   <img src="image.jpg"/>
</div>

收件人:

<div>
   <p><img src="image.jpg"/><br></p>
</div>

我尝试使用下面的代码,但无法更新到jsoup文档中

@Test
public void testaddp(){
    String acontent = "<div><img src="/base/img/avs.jpg"/></div>";
    Document document = Jsoup.parseBodyFragment(acontent);
    Element element = document.body();
    Element imgelement = element.select("img").first();
    Element newElement = new Element("p");
    newElement = newElement.insertChildren(0,imgelement,new Element("br"));
    System.out.println(newElement.outerHtml());//seems i got the correct html in newElement
    //imgelement.replaceWith(newElement);//failed to update into element
    imgelement.wrap(newElement.outerHtml());//also failed to update into element
    //how to updated into document?
    System.out.println();
}

2 个答案:

答案 0 :(得分:2)

尝试使用此代码。注释中的解释。

    String acontent = "<head>Some head</head><body><div>A div</div><div><img src=\"/base/img/avs.jpg\"/></div><div>Another div</div></body>";
    Document document = Jsoup.parse(acontent);
    System.out.println(document);
    //select element you want to change
    Element img = document.select("img").first();
    //wrap it with p
    Element p = new Element("p");
    p.html(img.outerHtml());
    //append br
    Element br = new Element("br");
    p.appendChild(br);
    //replace original with new
    img.replaceWith(p);

    System.out.println(document);

答案 1 :(得分:0)

我找到了一个答案:

@Test
public void testaddp(){
    String acontent = "<div><img src="/base/img/avs.jpg"/></div>";
    Document document = Jsoup.parseBodyFragment(acontent);
    Element element = document.body();
    Element imgelement = element.select("img").first();

    //find parent element
    Element parentElement = imgelement.parent();
    //add br after img tag
    parentElement.insertChildren(parentElement.childNodeSize(),new Element("br"));

    //add p tag out of img
    imgelement.wrap("<p>")

    System.out.println();
}