How do find an xml element by an attibute and delete it in java [duplicate]
Possible Duplicate:
How do I remove a node element by id in XML?
XML Structure
<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);
}
DESIRED OUTCOME
<Servers>
<server ID="42234">
&开发者_开发知识库lt;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>
You can use Xpath to get the Node then remove the node like you did in your code.
example:
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)
The broad answer is: Xpath. Xpath is a very expressive language that allows you to select nodes in your XML structure based on the structure and content of your XML document.
Specifically to your question, some code making use of xpath will go roughly like this
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
}
精彩评论