Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add namespace + prefix to XML using XSL

I hope you can help... Let's assume I have following XML:

<data>
   <token>
      <sessionId>12345</sessionId>         
      <userId>john</userId>
      <moreInfo>
         <bla> .....
         </bla>
      </moreInfo>
   </token>
</data>

And I need this to become

<login:data xmlns:login="http://my.ns.uri">
       <login:token>
          <login:sessionId>12345</sessionId>         
          <login:userId>john</userId>
          <login:moreInfo>
             <login:bla> .....
             </login:bla>
          </login:moreInfo>
       </login:token>
    </login:data>

Can I do this with XSL? I did try but failed miserably ... Any help would be greatly appreciated!

Thanks, Jan

like image 522
Jan Avatar asked May 10 '10 13:05

Jan


People also ask

How does xsl work with XML?

XSLT is used to transform XML document from one form to another form. XSLT uses Xpath to perform matching of nodes to perform these transformation . The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspective.

What is xsl namespace?

XSLT Elements The namespace name http://www.w3.org/1999/XSL/Transform is used primarily to identify elements which serve as declarations or instructions in the XSLT language.


1 Answers

Use:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:login="http://my.ns.uri">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*">
  <xsl:element name="login:{name()}" namespace="http://my.ns.uri">
    <xsl:copy-of select="namespace::*"/>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document, the wanted, correct result is produced:

<login:data xmlns:login="http://my.ns.uri">
   <login:token>
      <login:sessionId>12345</login:sessionId>
      <login:userId>john</login:userId>
      <login:moreInfo>
         <login:bla> .....
         </login:bla>
      </login:moreInfo>
   </login:token>
</login:data>
like image 101
Dimitre Novatchev Avatar answered Sep 28 '22 21:09

Dimitre Novatchev