Setting namespaces and schemas using java DOM
•
Java
There is a root element without attributes in my output XML document:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <root> .. </root>
I need it to look 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 using the Java DOM API
thank you!
Solution
Use ns method 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));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码