Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Deleting XML element in Java





I have an XML:

<?xml version="1.0" encoding="UTF-8"?>
            <artist>Ben Howard</artist>
            <title>Only Love</title>
            <artist>Ben Howard</artist>
            <title>Bad Blood</title>
            <title>Keep Your Head Up</title>
            <artist>Ben Howard</artist>

and my Java code is:

public static void deleteSong(Song song) {
        String songTitle = song.getTitle();
        String songArtist = song.getArtist();
        String songGenre = song.getGenre();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file = new File("songs.xml");
            Document doc = db.parse(file);

            NodeList songList = doc.getElementsByTagName("song");

            if (songList != null && songList.getLength() > 0) {
                for (int i = 0; i < songList.getLength(); i++) {

                    Node node = songList.item(i);
                    Element e = (Element) node;
                    NodeList nodeList = e.getElementsByTagName("title");
                    String title = nodeList.item(0).getChildNodes().item(0)
                    nodeList = e.getElementsByTagName("artist");
                    String artist = nodeList.item(0).getChildNodes().item(0)
                    nodeList = e.getElementsByTagName("genre");
                    String genre = nodeList.item(0).getChildNodes().item(0)
                    System.out.println(title + " Title");
                    System.out.println(songTitle + " SongTitle");

                    if (title.equals(songTitle)) {
                        if (artist.equals(songArtist)) {
                            if (genre.equals(songGenre)) {

        } catch (Exception e) {

The song to be deleted is passed into the method and then compared to the songs in the xml file. However, if the song matches a song in the xml, it isn't deleted? No exceptions come up.

like image 379
Ross Abrahams Avatar asked Mar 23 '23 20:03

Ross Abrahams

1 Answers

You need to remove relevant node, in you code you are removing node of firstchild which seems to be incorrect.

And write back your changes to the file.

 if (title.equals(songTitle) && artist.equals(songArtist) && genre.equals(songGenre) ) {


// write back to xml file

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
like image 187
Alpesh Gediya Avatar answered Apr 20 '23 06:04

Alpesh Gediya