i create a xml document with JAXP and search a way to insert the schemalocation. At the moment my application produces:
<?xml version="1.0" encoding="UTF-8"?>
<root>
...
</root>
But i need:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="namespaceURL"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="namespaceURL pathToMySchema.xsd">
...
</root>
My code:
StreamResult result = new StreamResult(writer);
Document doc = getDocument();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.VERSION, "1.0");
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(depl.getAsElement(doc));
trans.transform(source, result);
Thanks for your time,
Kasten
In XML data model namespace nodes are not actually read from parent element but each element has its own namespace nodes. Therefore simply adding a new default namespace to root element doesn't work but results in a document like this
Notice the appearing of empty default namespace
xmlns=""
on the child element(s). What actually needs to be done is to modify the namespace of every node or to create a new document with the desired default namespace and copy the contents, element and attribute names etc. of the old document to the new one. These can be done by recursively going through the original document. With Java DOM implementation this can be laborious, I've heard. One short cut might be to read the document with a namespace-unaware DOM and then add as attribute the new default namespace. Other solution is to change the namespace with an XSLT transformation, which seems quite suitable in this case, since you actually are already generating the output via XSLT transformation.Use this XSLT stylesheet to add a new default namespace and the schema location to the root element. This stylesheet preserves old namespaces but adds all elements to new default namespace if they previously were in no-namespace.
Instead of creating the transformer with
(which creates and stylesheet that does an identy transformation), create an XSLT input source and give it as a parameter to
newTransformer()
where
xsltFile
is aFile
object pointing to that XSLT file.Set the output properties as you wish and call
transform()
as in your sample code. The result should be what you desired, but I have not tested this in Java. The given XSLT file is tested for some trivial cases and there is a sample input and output at the end of this answer.Some minor notes:
transform()
method.xsi:
, notxs:
as in your example code (xs:
is used in schema definitions (as well asxsd:
)) .Sample input and output for the XSLT stylesheet shown above
Input:
Output: