2011-06-28 63 views
-1

可能重複:
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> 
+4

這一點已經在這裏找到答案你:http://stackoverflow.com/questions/6458890/how-do -i-除去-A-節點元件逐ID-在-XML/6459418#6459418 – adamjmarkham

回答

3

您可以使用XPath來獲取節點,然後刪除該節點就像你在你的代碼一樣。

例如:

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) 
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 
}