Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting namespace and schema using java dom

Tags:

java

dom

xml

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 Answers

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));
like image 140
McDowell Avatar answered Sep 11 '26 14:09

McDowell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!