Caleb
Caleb

Reputation: 621

Removing An Element From XML File Java

I have a xml file that contains this:

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

I want to remove one of them based on what a user inputs. What I have so far is

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

As you can see the program check to see if the name of the video typed is in the array list called videodatabase. If it is it opens the xml file and prepares to remove the video inputted. However I am stuck here. I want the xml file to look like:

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

Upvotes: 1

Views: 71

Answers (1)

vanje
vanje

Reputation: 10373

Here is the missing part using 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 ...

Upvotes: 1

Related Questions