从父级JSOUP中删除一个孩子

时间:2014-11-26 07:22:54

标签: android jsoup

<div id="standard">
    <div>textA</div>
   <div>textB</div>
   <div>textC</div>
   <div>textD</div>
   <div>textE</div>
   <div>textF</div>
   <div>textG</div>
</div>

我想从文档中删除最后一个div。

Document document = Jsoup.connect(url).get();
Elements myin = document.select("div#standard");
 myin.remove(6);

这不起作用。有人??

修改 我想删除第6个而不是最后一个。

1 个答案:

答案 0 :(得分:1)

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class Main {

    public static void main(String[] args) throws Exception {
        String html = "<div id=\"standard\">" +
                        "<div>textA</div>" +
                        "<div>textB</div>" +
                        "<div>textC</div>" +
                        "<div>textD</div>" +
                        "<div>textE</div>" +
                        "<div>textF</div>" +
                        "<div>textG</div>" +
                       "</div>";

        Document document = Jsoup.parse(html);
        Elements myin = document.select("div#standard");
        System.out.println(myin);
        System.out.println("------------------------------------------");

        /*
         * first() will return the element the div with id="standard". Because it's only one last() would do 
         * the same thing. Also get(0) would work.
         * children() returns all the child divs. 
         * last() will return the last element, and remove will cause its parent (div with id="standard")
         * to remove it.
         */
        myin.first().children().last().remove(); 
        //myin.last().children().last().remove(); 
        //myin.get(0).children().last().remove(); 

        System.out.println(myin);
    }
}

另一个解决方案是

Document document = Jsoup.parse(html);
Element myin = document.getElementById("standard");
System.out.println(myin);
System.out.println("------------------------------------------");
myin.children().last().remove(); 
System.out.println(myin);