I want to remove the specific nodes from xml file under song tag whose id =2 from the following file in Android (Java):

<music> <song> <id>1</id> <albums_id>1</albums_id> <title>Someone Like You</title> <artist>Adele</artist> <duration>4:47</duration> </song> <song> <id>2</id> <albums_id>1</albums_id> <title>Space Bound</title> <artist>Eminem</artist> <duration>4:38</duration> </song> <song> <id>3</id> <albums_id>1</albums_id> <title>Stranger In Moscow</title> <artist>Michael Jackson</artist> <duration>5:44</duration> </song> </music>

after deletion / removing the nodes (suppose id = 2) expected output needed

<music> <song> <id>1</id> <albums_id>1</albums_id> <title>Someone Like You</title> <artist>Adele</artist> <duration>4:47</duration> </song> <song> <id>3</id> <albums_id>1</albums_id> <title>Stranger In Moscow</title> <artist>Michael Jackson</artist> <duration>5:44</duration> </song> </music> 

Recommended Answers

All 3 Replies

What have you tried so far?
What exactly is it that you are stuck with?

    public static void removeName(String id) throws ParserConfigurationException, IOException, SAXException{
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("test.xml"));

            NodeList nodes = doc.getElementsByTagName("song");
            for (int i = 0; i < nodes.getLength(); i++) {       
                Element person = (Element)nodes.item(i);
                Element name = (Element)person.getElementsByTagName("id").item(0);
                String pName = name.getTextContent();
                if(pName.equals(id)){
                    person.getParentNode().removeChild(person);
                }
            }

        }

To delete node from xml use function given below

DocumentBuilderFactory dbf =
      DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));

  Document doc = db.parse(is);
  deletePerson(doc, id);



  public static void deletePerson(Document doc, String id) {
// <song>
NodeList nodes = doc.getElementsByTagName("song");

for (int i = 0; i < nodes.getLength(); i++) {
  Element person = (Element)nodes.item(i);
  // <name>
  Element name = (Element)person.getElementsByTagName("id").item(0);
  String pName = name.getTextContent();
  if (pName.equals(id)) {
     person.getParentNode().removeChild(person);
  }
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.