可能重複:
How do I remove a node element by id in XML?如何通過attibute找到一個XML元素,並在Java中刪除它
XML結構
<Servers>
<server ID="12234"> // <-- I want to find by this id and remove the entire node
<name>Greg</name>
<ip>127.0.0.1</ip>
<port>1897</port>
</server>
<server ID="42234">
<name>Bob</name>
<ip>127.0.0.1</ip>
<port>1898</port>
</server>
<server ID="5634">
<name>Tom</name>
<ip>127.0.0.1</ip>
<port>1497</port>
</server>
</Servers>
Java代碼:
public void removeNodeFromXML(String name)
throws ParserConfigurationException, SAXException, IOException,
TransformerException, XPathExpressionException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file_);
/**
* BEG FIX ME
*/
Element element = (Element) doc.getElementsByTagName(name).item(0);
// Remove the node
element.removeChild(element);
// Normalize the DOM tree to combine all adjacent nodes
/**
* END FIX ME
*/
doc.normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file_);
transformer.transform(source, result);
}
期望的結果
<Servers>
<server ID="42234">
<name>Bob</name>
<ip>127.0.0.1</ip>
<port>1898</port>
</server>
<server ID="5634">
<name>Tom</name>
<ip>127.0.0.1</ip>
<port>1497</port>
</server>
</Servers>
這一點已經在這裏找到答案你:http://stackoverflow.com/questions/6458890/how-do -i-除去-A-節點元件逐ID-在-XML/6459418#6459418 – adamjmarkham