michele
michele

Reputation:

problem with xslt and namespaces

I have a C# class that is serialized like this:

<oadResults 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://www.tyr.org.uk/standards"
>
  <Link>http://www.tyr.org.uk//290/Data.zip</Link>
  <ID>3540</ID>
</oadResults>

And I have a XSLT file:

<xsl:stylesheet 
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="/">
    ID <xsl:value-of select="ID"/>   </xsl:template>
</xsl:stylesheet>

The transformation does not work, the result is: "ID"

But if I delete this from the XML file:

xmlns="http://www.tyr.org.uk/standards"

It works fine and I get_ "ID:3540"

Can you tell me how I fix the problem changing the XSL file and not the XML?

Upvotes: 1

Views: 360

Answers (3)

Tomalak
Tomalak

Reputation: 338386

I would suggest:

<xsl:stylesheet 
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:tyr="http://www.tyr.org.uk/standards"
  exclude-result-prefixes="tyr"
>
  <xsl:template match="/tyr:oadResults">
    <xsl:text>ID </xsl:text>
    <xsl:value-of select="tyr:ID"/>   
    <xsl:text>&#10;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Note the <xsl:text> elements. They help to keep the XSL code clean (in terms of correct indentation) while ensuring a predictable output format.

exclude-result-prefixes prevents the tyr namespace declaration from appearing in the output.

Upvotes: 2

Stefan Gehrig
Stefan Gehrig

Reputation: 83662

You'll have to add the namespace to your XSLT.

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:t="http://www.tyr.org.uk/standards">
    <xsl:template match="/">
        ID <xsl:value-of select="t:ID"/>   
    </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Sir Rippov the Maple
Sir Rippov the Maple

Reputation: 7581

Try adding xmlns="http://www.tyr.org.uk/standards" to the xsl:stylesheet node of the XSLT document.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns="http://www.tyr.org.uk/standards" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    ID <xsl:value-of select="ID"/>   </xsl:template>
</xsl:stylesheet>

Alternatively, you can give the http://www.tyr.org.uk/standards namespace an alias in the XSLT doc, so it will look something like this:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:bob="http://www.tyr.org.uk/standards" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    ID <xsl:value-of select="bob:ID"/>   </xsl:template>
</xsl:stylesheet>

You can find more information about xml namespaces at http://www.w3.org/TR/REC-xml-names/

Upvotes: 0

Related Questions