2017-05-27 66 views
1

我有一個包含這一個xml文件:移除元素從XML文件的Java

<class> 
<Video>Spiderman</Video> 
<Video>Superman</Video> 
</class> 

我想刪除基於什麼用戶輸入其中之一。我至今是

for (int x=0; x<videodatabase.size(); x++) { 
      if (inputVideo.getText().contentEquals(videodatabase.get(x))) { 
       try { 
        String filepath = "videodatabase.xml"; 
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
        Document doc = docBuilder.parse(filepath); 

        // I want to remove the <Video>name of the video</Video> from the xml here. 

        TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
        Transformer transformer = transformerFactory.newTransformer(); 
        DOMSource source = new DOMSource(doc); 
        StreamResult result = new StreamResult(new File(filepath)); 
        transformer.transform(source, result); 
       }  
       catch(ParserConfigurationException pce){ 
        pce.printStackTrace(); 
       } 
       catch(TransformerException tfe){ 
        tfe.printStackTrace(); 
       } 
       catch(IOException ioe){ 
        ioe.printStackTrace(); 
       } 
       catch(SAXException sae){ 
        sae.printStackTrace(); 
       } 
      } 
     } 

正如你可以看到程序檢查,看是否輸入視頻的名字是叫videodatabase數組列表。如果它是打開xml文件並準備刪除輸入的視頻。但是我在這裏卡住了。我想xml文件看起來像:

<class> 
<Video>Spiderman</Video> 
</class> 
+0

有幾種方法來操作XML在Java中。當你使用TransformerFactory時,顯然你想使用XSLT,所以真正的問題是:「如何使用XSLT去除元素」。順便說一句,你應該將XSLT模板傳遞給newInstance()調用。另一種方法是使用JAXB創建xml的遠程一個元素的java模型,然後再將它串行化爲xml。 – Peter

+0

我不同意@Peter。使用「TransformerFactory」是序列化DOM文檔的標準方式。這並不意味着必須自動使用XSLT。我認爲使用簡單的DOM操作移除一個節點要比使用XSLT移除更容易。 – vanje

回答

1

這裏是缺失的部分使用XPath:

// Get a XPath instance 
XPath xpath = XPathFactory.newInstance().newXPath(); 
// Find the Video element with text 'Superman' 
Element supermanVideo = (Element) xpath.evaluate("/class/Video[. = 'Superman']", 
    doc, XPathConstants.NODE); 
if(supermanVideo != null) { 
    // Remove this element from the parent 
    supermanVideo.getParentNode().removeChild(supermanVideo); 
} 
// Serialize the XML document ... 
+0

而不是使用字面超人,你可以使用陣列?更新答案的積分... – Thufir