How to avoid adding XMLNS when using using Java XML Transformer?
In JAVA I copy nodes from one XML document to another new document using importNode. In original document there is an 开发者_运维知识库xmlns defined, but in output document I would like to not have xmlns defined per each element that I copied. How to do it?
It depends what you mean. When an XML document has an xmlns, it is really a shorthand for the element names; e.g. if the xmlns is "http://example.com/#" then the true element name for
<foo attr="xxx">...</foo>
is http://example.com/#foo
, which you would write without an xmlns as
<http://example.com/#foo attr="xxx">...</http://example.com/#foo>
If you want your output XML to look like that, it should be possible to achieve it by tweaking the XML writer parameters.
If you want your output XML to look like the original, but without the xmlns, you are actually changing the meaning of the XML. The clean way to do this would be to use an XSL transformer.
You say that you are using the Java XML Transformer, but it's not clear whether you mean the identity transformer (TransformerFactory.newTransformer()) or the Java interface to an XSLT transformation.
It sounds to me as if you are using an operation that copies the document when you need an operation that transforms it, for example by changing the element names.
Using javax.xml.transform.Transformer with XSL defined as below seems to be a good solution:
String stylesheet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +
"<xsl:output method=\"xml\" version=\"1.0\" indent=\"no\"/>" +
"<xsl:template match=\"*\">" +
"<xsl:element name=\"{local-name()}\">" +
"<xsl:for-each select=\"@*\">" +
"<xsl:attribute name=\"{local-name()}\">" +
"<xsl:value-of select=\".\"/>" +
"</xsl:attribute>" +
"</xsl:for-each>" +
"<xsl:apply-templates/>" +
"</xsl:element>" +
"</xsl:template>" +
"</xsl:stylesheet>";
StreamSource xslSource = new StreamSource(new StringReader(stylesheet));
Transformer transformer = tf.newTransformer(xslSource);
精彩评论