如何从xml中删除节点?
Posted
技术标签:
【中文标题】如何从xml中删除节点?【英文标题】:How to remove node from xml? 【发布时间】:2019-04-12 16:44:44 【问题描述】:我有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 的节点,我该怎么做?
我尝试这样做,但日志显示在长度 = 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】:对我有帮助的解决方案:
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());
【讨论】:
以上是关于如何从xml中删除节点?的主要内容,如果未能解决你的问题,请参考以下文章