java - How to add namespace declaration to root element of DOM? -


i need (well, love...) add namespace declaration root element of dom tree. repeatedly use namespace later in document, , it's not handy have declaration in each node use it:

<?xml version="1.0" encoding="utf-8" standalone="no"?><test>    <value xmlns:test="urn:mynamespace" test:id="1">42.42</value>    <value2 xmlns:test="urn:mynamespace" test:id="2">hello namespace!</value2> </test> 

what i'd is

<?xml version="1.0" encoding="utf-8" standalone="no"?><test xmlns:test="urn:mynamespace">    <value test:id="1">42.42</value>    <value2 test:id="2">hello namespace!</value2> </test> 

which more convenient when later editing hand.

i know it's possible, because when load document contains

<test xmlns:test="urn:mynamespace"> </test> 

and add remaining nodes.

so think questions boils down to: how add xmlns:test="urn:mynamespace" root node? when try add attribute, namespace_err exception (i use namespace-aware factory, etc). because try mess namespaces bypassing api can't find...

note: there no attribute using namespace in root element (when allow that, can work), namespace declaration.

with xslt document

<xsl:stylesheet version="1.0"     xmlns:xsl="http://www.w3.org/1999/xsl/transform"     xmlns:test="urn:mynamespace">  <xsl:output indent="yes" standalone="no" encoding="utf-8"/>  <!-- copies root element , contents --> <xsl:template match="/*" priority="2">     <xsl:element name="{name()}" namespace="{namespace-uri()}">         <xsl:copy-of select="namespace::*"/>         <xsl:copy-of select="document('')/*/namespace::*[name()='test']"/>         <xsl:copy-of select="@*"/>         <xsl:copy-of select="*"/>     </xsl:element> </xsl:template>  <!-- copies comments, processing instructions etc. outside      root element. not neccesarily needed. --> <xsl:template match="/node()">     <xsl:copy-of select="."/> </xsl:template>  </xsl:stylesheet> 

given input (your code example)

<?xml version="1.0" encoding="utf-8" standalone="no"?> <test>    <value xmlns:test="urn:mynamespace" test:id="1">42.42</value>    <value2 xmlns:test="urn:mynamespace" test:id="2">hello namespace!</value2> </test> 

results in desired output

<?xml version="1.0" encoding="utf-8" standalone="no"?> <test xmlns:test="urn:mynamespace">   <value test:id="1">42.42</value>   <value2 test:id="2">hello namespace!</value2> </test> 

you can perform xslt transformations in java transformer class.

javax.xml.transform.source xsltsource = new javax.xml.transform.stream.streamsource(xsltfile); transformer transformer = transformerfactory.newinstance().newtransformer(xsltsource); 

where xsltfile file object pointing xslt file.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -