如何从xml中删除节点?

时间:2018-11-09 05:12:52

标签: android xml parsing dom

我有xml:

<Info>
    <info_1/>
    <info_2/>
    <info_3>
        <i ID="1"/>
        <i ID="2"/>
        <i ID="3"/>
    </info_3>
    <info_4>
    </indo_4>
</Info>  

我需要删除info_3中的特定节点,例如ID = 1的节点,我该怎么做?

我试图这样做,但是log显示length = 3前后:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();  

NodeList nList = doc.getElementsByTagName("i");  
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Node node=nList.item(1);  
node.getParentNode().removeChild(node);  
Log.e("LOG", "nList.getLength() = " + nList.getLength());

1 个答案:

答案 0 :(得分:0)

对我有帮助的解决方案:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();  

NodeList nList = doc.getElementsByTagName("i");  
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Set<Element> targetElements = new HashSet<>();
for (int i = 0; i < nList_Loan_guarantor.getLength(); i++) {
  Element e = (Element)nList_Loan_guarantor.item(i);
  if ("10938".equals(e.getAttribute("ID"))) {
  targetElements.add(e);
  }
}

for (Element e: targetElements) {
   e.getParentNode().removeChild(e);
   }

doc.getDocumentElement().normalize();
NodeList nList_2 = doc.getElementsByTagName("i"); 
Log.e("LOG", "nList.getLength() = " + nList.getLength());