如何通过 XML 中的 id 删除节点元素? [英] How do I remove a node element by id in XML?

查看:34
本文介绍了如何通过 XML 中的 id 删除节点元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:javax.xmlorg.w3c:

public void removeNodeFromXML(File xmlfile_, String uuid)
  {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xmlfile_);

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer tFormer = tFactory.newTransformer();

   //????

   Element rootElement = doc.getRootElement();
   rootElement.removeChild("1236");

   //???

   // Normalize the DOM tree to combine all adjacent nodes
   doc.normalize();
   Source source = new DOMSource(doc);
   Result dest = new StreamResult(xmlfile_);
   tFormer.transform(source, dest);

  }

XML 看起来像这样

<Servers>
 //remove this guy
 <server ID="1236">
  <name>Josh</name>
  <port>1234</port>
  <ip>12.2.2.3</ip>
 </server>

<server ID="1237">
  <name>John</name>
  <port>1234</port>
  <ip>12.2.2.3</ip>
 </server>
</Servers>

推荐答案

您可以使用 XPath 来选择特定的元素/属性.只需在网上搜索教程.这里很好.您还应该阅读java.xml.xpath 的 Java-Doc,其中包括简短的示例.

You can use XPath to select specific elements/attributes. Just search the web for Tutorials. Here is good one. You should also read the Java-Doc for java.xml.xpath, which includes short examples.

XML 文件的 XPath 表达式为:/server[@ID='xxxx']

The XPath-Expression for your XML-File is: /server[@ID='xxxx']

这篇关于如何通过 XML 中的 id 删除节点元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆