【问题标题】:Replace open and close tag?替换打开和关闭标签?
【发布时间】:2016-04-02 00:00:46
【问题描述】:

我有一个需要替换特定标签的 html/xml 文件。我遇到了以下 xml 的问题:

<section>
    <banner>
</section>

我可以用以下解决方案替换&lt;banner&gt; 标签: Replacing tag with letters using JSoup

但是我遇到了带有子标签的问题,例如: 将&lt;section&gt; 替换为&lt;mysection&gt;&lt;b&gt;,将&lt;/section&gt; 替换为&lt;/b&gt;&lt;/mysection&gt;

(当然保留&lt;section&gt;标签的子元素)

我试过了:

els = doc.select("section");
els.tagName("mysection");

但我也希望添加&lt;b&gt; 标签(以及更多)。

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    这个怎么样

    // sample data: a parent section containing nodes
    String szHTML = "<section><banner><child>1</child></banner><abc></abc></section>";
    
    Document doc = Jsoup.parse(szHTML);
    
    // select the element section
    Element sectionEle = doc.select("section").first();
    
    // renaming the section element to mysection
    sectionEle.tagName("mysection");
    
    // get all the children elements of section element
    Elements children = sectionEle.children();
    
    // remove all the children
    for(Node child: children){
        child.remove();
    }
    
    // insert element b in mysection
    Element b = sectionEle.appendElement("b");
    
    // insert all the child nodes back to element b
    b.insertChildren(0, children);
    
    
    System.out.println(doc.toString());
    

    期望的输出:

      <mysection>
       <b>
        <banner>
         <child>
          1
         </child>
        </banner>
        <abc></abc></b>
      </mysection>
    

    【讨论】:

    • 赞赞桑迪普!这就像一个魅力,在 insertChildren 上找到了很好的发现。
    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2011-07-13
    • 2019-06-18
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多