-3

I have this XML file

enter image description here

I need function in Java which can remove the username node.

I use function remove()

public void remove(String username){
    // what do I write here to remove node of the username?
}

For example I need to remove element "anas":

remove("anas")

and the result is

enter image description here

alex
  • 10,900
  • 15
  • 70
  • 100

1 Answers1

0

Try this code

package com.sree;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;

import org.w3c.dom.*;

public class Test {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document = dbf.newDocumentBuilder().parse(
                new File("input.xml"));

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath
                .compile("//data/user/username[text()='simple']");
        Node b13Node = (Node) expression
                .evaluate(document, XPathConstants.NODE);
        b13Node = b13Node.getParentNode();
        b13Node.getParentNode().removeChild(b13Node);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }

}