I have an unusual request. I need to generate an xml file that looks for eg., something like below
<?xml version="1.0" encoding="UTF-8"?>
<pk:DeviceInfo xmlns:pk="urn:ietf:params:xml:ns:kyp:pk" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<pk:Manufacturer xmlns:pk="urn:ietf:params:xml:ns:kyp:pk" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
ABC
</pk:Manufacturer>
<pk:SerialNo>123456</pk:SerialNo>
<pk:Model>Model1</pk:Model>
<pk:IssueNo>1</pk:IssueNo>
</pk:DeviceInfo>
I am generating the xml using jdom api. The problem is, even if i declare namespace for pk:Manufacturer element, jdom doesn't add it there because it is already declared in the root element. But i need to repeat the namespace declaration in the child element as well, because i need to send this file to another server that requires the xml to be in this format.
I believe jdom doen't allow this, so i tried to create the xml first with jdom and update the xml with dom parser to include the namespace to the child element using elmt.setAttributeNS(), but unfortunately this doesn't seem to work.
Has anybody faced this problem before?
You haven't shown us which DOM code you tried but when I test
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
String ns1 = "http://example.com/ns1";
String ns2 = "http://example.com/ns2";
Element root = doc.createElementNS(ns1, "pf1:root");
root.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf2", ns2);
doc.appendChild(root);
Element foo = doc.createElementNS(ns1, "pf1:foo");
foo.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf1", ns1);
foo.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:pf2", ns2);
root.appendChild(foo);
DOMImplementationLS domImp = (DOMImplementationLS)doc.getImplementation();
LSSerializer ser = domImp.createLSSerializer();
System.out.println(ser.writeToString(doc));
with Oracle Java 1.8 the output is
<pf1:root xmlns:pf1="http://example.com/ns1" xmlns:pf2="http://example.com/ns2"><pf1:foo xmlns:pf1="http://example.com/ns1" xmlns:pf2="http://example.com/ns2"/></pf1:root>
thus the explicitly created namespace attribute declarations on the child are serialized. So that should be a way for the W3C DOM, explicitly create namespace declarations on the elements you need them and use LSSerializer to write out the tree.