Frage

I'm trying to use XSLT to check for an attribute (with namespace) value and change the value of the tag.

Input:

<Datalist> 
     <username xmlns="http:sps.in" nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 
</Datalist>

Required Output:

Input:

<Datalist> 
     <username xmlns="http:sps.in" nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">NULL</Datalist> 
</Datalist>

I wrote following XSL and it works when there is no namespaces. How should I change it to work with namespaces?

<xsl:stylesheet version="2.0" xmlns="http:sps.in" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
   <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

<xsl:template match="Datalist/username">
  <xsl:choose>
    <xsl:when test="@nil='true'">
         <username>NULL</username>
    </xsl:when>
    <xsl:otherwise>
        <username>NOTNULL</username>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

</xsl:stylesheet>
War es hilfreich?

Lösung

While XSLT 2.0 supports xpath-default-namespace to set the namespace URI that is assumed for non-prefixed names, that won't help you here as you need to match a namespaced element that is a child of a non-namespaced one.

You must bind a prefix to http:sps.in in the stylesheet and then use that in the match expression:

<xsl:stylesheet version="2.0" xmlns="http:sps.in" xmlns:sps="http:sps.in"
    exclude-result-prefixes="sps"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- ... -->

  <xsl:template match="Datalist/sps:username">

The @nil should still work as the nil attribute in your example is not itself in a namespace. If it were xsi:nil then you would need to bind the xsi prefix in your stylesheet in the same way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top