Java HTML / XML How to - Update the input XML file with namespce in JAVA using DOM parser


We would like to know how to update the input XML file with namespce in JAVA using DOM parser.


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
/*from   w ww .j  a v  a 2 s.  c  om*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    // Create original document
    Document document = db.newDocument();
    Element root = document.createElementNS("urn:FOO", "ns0:Root");
    Element request = document.createElementNS("urn:FOO", "ns0:Request");

    // Create new Request element.
    Element newRequest = document.createElementNS("urn:BAR", "ns1:Request");

    // Replace Request element
    root.replaceChild(newRequest, request);

    // Output the new document
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(System.out);
    t.transform(source, result);