Java HTML / XML How to - Create Element with namespace, fully qualified








Question

We would like to know how to create Element with namespace, fully qualified.

Answer

/*from w w  w.  java  2s. co m*/
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
  public static void main(String[] argv) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder loader = factory.newDocumentBuilder();
    Document document = loader.newDocument();
    edit(document);

    System.out.println(documentToString(document));

  }
  public static void edit(Document document) {
    String docNS = "http://www.my-company.com";

    Element order = document.createElementNS(docNS, "order");
    document.appendChild(order);
    order.setAttribute("xmlns", docNS);
  }


  public static String documentToString(Document document) {
    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer trans = tf.newTransformer();
      StringWriter sw = new StringWriter();
      trans.transform(new DOMSource(document), new StreamResult(sw));
      return sw.toString();
    } catch (TransformerException tEx) {
      tEx.printStackTrace();
    }
    return null;
  }
}

The code above generates the following result.