【问题标题】:remove one child from a parent JSOUP从父 JSOUP 中删除一个孩子
【发布时间】:2014-11-26 07:22:53
【问题描述】:
<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 个,而是最后一个。

【问题讨论】:

    标签: android jsoup


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2012-11-05
      • 2020-09-18
      • 2018-08-19
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多