Home > OS >  Java: How to build a XML with namespace
Java: How to build a XML with namespace

Time:01-25

I try to create a XML DOM with a namespace - but not sure how to do it.

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

public class App 
{
    public static void main (String args []) throws Exception
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
        DocumentBuilder db = dbf.newDocumentBuilder ();
        Document doc = db.newDocument ();
            
        Element env = doc.createElement ("Env");
        env.setAttributeNS ("aaa", "bbc", "ccc");
        doc.appendChild (env);
            
        TransformerFactory tf = TransformerFactory.newInstance ();
        Transformer tr = tf.newTransformer ();
        StringWriter sw = new StringWriter ();
        tr.transform (new DOMSource (doc), new StreamResult (sw));
        System.out.println (sw.toString ());
    }
}

Result is

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Env xmlns:ns0="aaa" ns0:bbb="ccc"/>

But what I want is

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Env xmlns:aaa="bbb"/>

How can I get that?

CodePudding user response:

Setting the attribute directly by using setAttribute() outputs your desired result.

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();

    // You might also want to consider setting your 
    // DocumentBuilderFactory to be namespace aware by using
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder ();
    Document doc = db.newDocument ();

    Element env = doc.createElement ("Env");
    //   env.setAttributeNS ("aaa", "bbc", "ccc");
    env.setAttribute("xmlns:aaa", "bbb");
    doc.appendChild (env);

    TransformerFactory tf = TransformerFactory.newInstance ();
    Transformer tr = tf.newTransformer ();
    StringWriter sw = new StringWriter ();
    tr.transform (new DOMSource (doc), new StreamResult (sw));
    System.out.println (sw.toString ());

output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Env xmlns:aaa="bbb"/>
  •  Tags:  
  • Related