3

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!

1
  • ah, you beat me to the edit! Thanks! Commented Nov 11, 2009 at 18:33

1 Answer 1

7

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.