Search code examples
javaxmlnamespacesxmldocumentxom

Creating an XML document using namespaces in Java


I am looking for example Java code that can construct an XML document that uses namespaces. I cannot seem to find anything using my normal favourite tool so was hoping someone may be able to help me out.


Solution

  • I am not sure, what you trying to do, but I use jdom for most of my xml-issues and it supports namespaces (of course).

    The code:

    Document doc = new Document();
    Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
    Element element = new Element("SomeElement", sNS);
    element.setAttribute("someKey", "someValue", Namespace.getNamespace("someONS", "someOtherNamespace"));
    Element element2 = new Element("SomeElement", Namespace.getNamespace("someNS", "someNamespace"));
    element2.setAttribute("someKey", "someValue", sNS);
    element.addContent(element2);
    doc.addContent(element);
    

    produces the following xml:

    <?xml version="1.0" encoding="UTF-8"?>
     <someNS:SomeElement xmlns:someNS="someNamespace" xmlns:someONS="someOtherNamespace"  someONS:someKey="someValue">
      <someNS:SomeElement someNS:someKey="someValue" />
     </someNS:SomeElement>
    

    Which should contain everything you need. Hope that helps.