2016-04-01 198 views
1

我有一个html/xml文件需要替换特定的标签。我遇到麻烦,下面的XML:替换打开和关闭标记?

<section> 
    <banner> 
</section> 

我可以像解决方案替换<banner>标签: Replacing tag with letters using JSoup

但我遇到麻烦,有孩子,例如标签: 替换<section><mysection><b></section></b></mysection>

(当然保持<section>标签的孩子)

我想:

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

,但我也想加入的<b>标签(多一点)。

回答

2

这个怎么样

// 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> 
+1

竖起大拇指桑迪普!这工作就像一个魅力,在insertChildren一个很好的发现。 –