使用:javax.xml
和org.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>
答案 0 :(得分:3)
您可以使用XPath选择特定元素/属性。只需在网上搜索教程。 Here is good one.您还应该阅读Java-Doc for java.xml.xpath,其中包含简短的示例。
XML文件的XPath表达式为:/server[@ID='xxxx']
答案 1 :(得分:0)
您可以使用:
Element element = doc.getElementById("1236");
element.getParentNode().removeChild(element);
这应该为您提供ID为“1236”的元素。然后,您获取元素的父节点,并通过将ID为“1236”的元素传递给removeChild来删除元素。
希望这有帮助。