adding namespace and namespace prefix using dom4j

user1487454 picture user1487454 · Nov 2, 2012 · Viewed 8.5k times · Source

i am updating one xml using dom4j as below.

    SAXReader reader = new SAXReader();
document = reader.read( xmlFileName );

but it removes all namespaces from the elements so wanna add manually but it does not work when i tried the following code.

    Element e1 = root.addElement("jmsProducer");   
    e1.addNamespace("AEService", "http://www.tibco.com/xmlns/aemeta/services/2002");

my xml looks like

    <AEService:jmsProducer objectType="endpoint.JMSPublisher" name="Pub1EndPoint">  
    <AEService:wireFormat>aeXml</AEService:wireFormat>

which sud look like

    <AEService:jmsProducer xmlns:AEService="http://www.tibco.com/xmlns/aemeta/services   /2002" objectType="endpoint.JMSPublisher" name="Pub1EndPoint">
    <AEService:wireFormat>aeXml</AEService:wireFormat>

any help is highly appriciated. banging on this for two days tried using documentfactory method still no use.

Answer

Sujit Pal picture Sujit Pal · Jul 17, 2015

I realize that this is an old thread, and dom4j may not have had adequate namespace capabilities at the time the answers were written, but it looks like dom4j is now able to accomplish this quite easily with the version I am using (1.6.1). I came here looking for help on how to build a namespace aware XML with dom4j, posting my Java code (to build the XML snippet in the original post) in case it helps someone.

Here is the Java code to build it.

Document xmldoc = DocumentHelper.createDocument();
Namespace aeServiceNs = new Namespace("AEService",
  "http://www.tibco.com/xmlns/aemeta/services/2002");
Element root = xmldoc.addElement(new QName("jmsProducer", aeServiceNs))
                     .addAttribute("objectType", "endpoint.JMSPublisher")
                     .addAttribute("name", "Pub1EndPoint");
Element wireformat = root.addElement(new QName("wireFormat", aeServiceNs))
                         .setText("aeXml");
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
XMLWriter xmlwriter = new XMLWriter(System.out, outputFormat);
xmlwriter.write(xmldoc);

produces this output:

<?xml version="1.0" encoding="UTF-8"?>

<AEService:jmsProducer 
    xmlns:AEService="http://www.tibco.com/xmlns/aemeta/services/2002" 
    objectType="endpoint.JMSPublisher" name="Pub1EndPoint">
  <AEService:wireFormat>aeXml</AEService:wireFormat>
</AEService:jmsProducer>

Hope this helps.