GraciousBen Howard

Removing an XML Element in Java

I have XML:

<?xml version="1.0" encoding="UTF-8"?> <songs> <song> <title>Gracious</title> <artist>Ben Howard</artist> <genre>Singer/Songwriter</genre> </song> <song> <title>Only Love</title> <artist>Ben Howard</artist> <genre>Singer/Songwriter</genre> </song> <song> <title>Bad Blood</title> <artist>Bastille</artist> <genre>N/A</genre> </song> <song> <title>Keep Your Head Up</title> <artist>Ben Howard</artist> <genre>Singer/Songwriter</genre> </song> <song> <title>Intro</title> <artist>Alt-J</artist> <genre>Alternative</genre> </song> </songs> 

and my java code:

 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) .getNodeValue(); nodeList = e.getElementsByTagName("artist"); String artist = nodeList.item(0).getChildNodes().item(0) .getNodeValue(); nodeList = e.getElementsByTagName("genre"); String genre = nodeList.item(0).getChildNodes().item(0) .getNodeValue(); System.out.println(title + " Title"); System.out.println(songTitle + " SongTitle"); if (title.equals(songTitle)) { if (artist.equals(songArtist)) { if (genre.equals(songGenre)) { doc.getFirstChild().removeChild(node); } } } } } MainDisplay.main(null); } catch (Exception e) { System.out.println(e); } } 

The song to be deleted is passed to the method and then compared to the songs in the xml file. However, if a song matches a song in xml, is it not deleted? There are no exceptions.

+4
source share
2 answers

You need to remove the corresponding node, in your code you remove the node from firstchild, which seems to be wrong.

And write your changes to the file.

  if (title.equals(songTitle) && artist.equals(songArtist) && genre.equals(songGenre) ) { node.getParentNode().removeChild(node); } 

// write back to the 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); 
+4
source

From what I see, you are only reading documents. At some point you will have to flush the changes back to the XML file.

+3
source

Source: https://habr.com/ru/post/1482734/


All Articles