Leonel
Leonel

Reputation: 29189

Java XML: how to output the namespace of child elements?

I'm using Java's Transformer class to process an XML Document object.

This is the code that creates the Transformer:

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

transformer.transform(source, result);

Currently, my output looks like this: <svg ... />. I'd like it to include the namespace of each element, as in <svg:svg ... />

How can I do that ?

Upvotes: 3

Views: 4790

Answers (3)

Ted Johnson
Ted Johnson

Reputation: 4343

What I found is that you need to put it on yourself as a prefix, not even use the namespaces.

I used el.setAttribute("xmi:type", type) for example rather than el.setAttributeNS("xsi", "type", type); or el.setAttributeNS("http://www...../URI", "type", type); I am finding that the NS method does not do quite what you thing it will do. Additionally it will still render it xmlns="..." rather than using the prefix.

Upvotes: 0

phihag
phihag

Reputation: 287745

Note that <svg xmlns="SVGNS" /> is the same as <svg:svg xmlns:svg="SVGNS" />.

Did you check you called setNamespaceAware(true) on your DocumentBuilderFactory instance ?

Upvotes: 2

Ken Gentle
Ken Gentle

Reputation: 13357

The package description for javax.xml.transform has a section Qualified Name Representation which seems to imply that it is possible to get the namespace represented in both input and output.

It isn't really clear to me what the result would look like, other than the namespace URI would be included.

Give it a try - hopefully someone else will have more concrete experience.

Upvotes: 0

Related Questions