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 CODE:
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>
答案 0 :(得分:3)
您可以使用Xpath获取Node,然后像在代码中一样删除节点。
示例:
XPathExpression expr = xpath.compile("Server/server[@id="+idToBeDeleted+"]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result;
//if you have atleast 1
Node nodeToBeRemoved = nodes.item(0)
答案 1 :(得分:2)
答案很广泛: Xpath 。 Xpath是一种非常富有表现力的语言,允许您根据XML文档的结构和内容选择XML结构中的节点。
特别是对于你的问题,一些使用xpath的代码大致会像这样
String xpath = "/Servers/server/*[@id='<your data goes here']";
NodeList nodelist = XPathAPI.selectNodeList(doc, xpath);
if (nodelist.getLength()==1) { // you found the node, and there's only one.
Element elem = (Element)nodelist.item(0);
... // remove the node
}