public static Element toDOM(OMElement element, Document doc, boolean deepNS) {
final Element domElement = doc.createElementNS(element.getQName().getNamespaceURI(),
element.getQName().getLocalPart());
if (deepNS) {
NSContext nscontext = new NSContext();
buildNScontext(nscontext, element);
DOMUtils.injectNamespaces(domElement,nscontext);
} else {
if (element.getAllDeclaredNamespaces() != null) {
for (Iterator i = element.getAllDeclaredNamespaces(); i.hasNext(); ) {
OMNamespace omns = (OMNamespace)i.next();
if (omns.getPrefix().equals("")) {
domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns",
omns.getNamespaceURI() == null ? "" :
omns.getNamespaceURI());
}
else {
domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:"+ omns.getPrefix(),
omns.getNamespaceURI());
}
}
}
}
for (Iterator i = element.getAllAttributes(); i.hasNext();) {
final OMAttribute attr = (OMAttribute) i.next();
Attr newAttr;
if (attr.getNamespace() != null) {
newAttr = doc.createAttributeNS(attr.getNamespace().getNamespaceURI(),
attr.getLocalName());
} else {
newAttr = doc.createAttributeNS(null,attr.getLocalName());
}
newAttr.appendChild(doc.createTextNode(attr.getAttributeValue()));
domElement.setAttributeNodeNS(newAttr);
// Case of qualified attribute values, we're forced to add corresponding namespace declaration manually...
int colonIdx = attr.getAttributeValue().indexOf(":");
if (colonIdx > 0) {
OMNamespace attrValNs = element.findNamespaceURI(attr.getAttributeValue().
substring(0, colonIdx));
if(attrValNs!=null) {
domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:"+ attrValNs.getPrefix(),
attrValNs.getNamespaceURI());
}
}
}
for (Iterator i = element.getChildren(); i.hasNext();) {
OMNode omn = (OMNode) i.next();
switch (omn.getType()) {
case OMNode.CDATA_SECTION_NODE:
domElement.appendChild(doc.createCDATASection(((OMText)omn).getText()));
break;
case OMNode.TEXT_NODE:
domElement.appendChild(doc.createTextNode(((OMText)omn).getText()));
break;
case OMNode.ELEMENT_NODE:
domElement.appendChild(toDOM((OMElement)omn,doc, false));
break;
}
}
return domElement;
}