tags:

views:

98

answers:

1

I have a root element in my output xml document that has no attributes:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
..
</root>

I need it to look something like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="my.xsd">
....
</root>

I can't figure out how to do this correctly with the java DOM API.

Thanks!

+2  A: 

Use the NS methods. In this case, the namespace is http://www.w3.org/2001/XMLSchema-instance.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("root");
root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
    "xsi:noNamespaceSchemaLocation", "my.xsd");
root.appendChild(doc.createElement("foo"));
doc.appendChild(root);
// see result
DOMImplementationLS dls = (DOMImplementationLS) doc.getImplementation();
System.out.println(dls.createLSSerializer().writeToString(doc));
McDowell