MrD at KookerellaLtd
MrD at KookerellaLtd

Reputation: 2795

how to generate elements inside source xml namespace (xslt 1.0)

I have a simple xml I'm trying to process, something like

<?xml version="1.0" encoding="utf-8"?>
<root>
  <foo>1234</foo>
</root>

with an xslt...I want to inject data into this xml to then process it into an excel...so something horrid like this...in psuedo xslt 1.0..but with the relevant piece

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:kooks ="http://kookerella.com" exclude-result-prefixes="kooks msxsl">
   <xsl:template match="/root">
      <xsl:variable name="bar">
         <xsl:choose>
            <xsl:when test="...">
               <xsl:copy-of select="foo"/>
            </xsl:when>
            <xsl:otherwise>
               <foo>5678</foo>
            </xsl:otherwise>
         </xsl:choose>
      </xsl:variable>
      <xsl:foreach select="msxml:node-set($bar)/foo">
        ...do some stuff...
      </xsl:foreach>
   </xsl:template>
</xsl:stylesheet>

now the issue is that the "foo" element I define inside the xslt is in a different namespace (I think), so it isnt matched in the "foreach" processing section...so how do I force this xslt element to live in the correct namespace?

Upvotes: 0

Views: 21

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116993

Your stylesheet declares a default namespace:

xmlns="urn:schemas-microsoft-com:office:spreadsheet" 

Not sure why this is needed. While it's there, any element created by the stylesheet will inherit this namespace - specifically foo in:

        <xsl:otherwise>
           <foo>5678</foo>
        </xsl:otherwise>

You could prevent this by placing the created element explicitly in no namespace:

        <xsl:otherwise>
           <foo xmlns="">5678</foo>
        </xsl:otherwise>

but there is probably a better way to accomplish whatever purpose this is supposed to accomplish.


P.S. Your title says "how to generate elements inside source xml namespace" - but the source XML has no namespace. If you want to place the copied element in the default namespace, you must recreate it in the target namespace, not copy it. Copy means copy - including the original namespace.

Upvotes: 1

Related Questions