get xml attribute named xlink:href using xsl
Asked Answered
V

2

5

How can I get the value of an attribute called xlink:href of an xml node in xsl template?

I have this xml node:

<DCPType>
 <HTTP>
  <Get>
   <OnlineResource test="hello" xlink:href="http://localhost/wms/default.aspx" 
      xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" />
  </Get>
 </HTTP>
</DCPType>

When I try the following xsl, I get an error saying "Prefix 'xlink' is not defined." :

<xsl:value-of select="DCPType/HTTP/Get/OnlineResource/@xlink:href" />

When I try this simple attribute, it works:

<xsl:value-of select="DCPType/HTTP/Get/OnlineResource/@test" />
Vexillum answered 6/5, 2010 at 8:21 Comment(1)
Good Question (+1). See my answer for an alternative solution. :)Plumper
D
11

You need to declare the XLINK namespace in your XSLT before you can reference it.

You could add it to the xsl:value-of element:

<xsl:value-of select="DCPType/HTTP/Get/OnlineResource/@xlink:href" xmlns:xlink="http://www.w3.org/1999/xlink" />

However, if you are going to need to reference it in other areas of your stylesheet, then it would be easier to declare it at the top in the document element of your XSLT:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:xlink="http://www.w3.org/1999/xlink">

Incidentally, you don't need to use the same namespace prefix in your stylesheet as what is used in your XML. The namespace prefix is just used as shorthand for the namespace URI. You could declare and use the XLINK namespace like this:

<xsl:value-of select="DCPType/HTTP/Get/OnlineResource/@x-link:href"  xmlns:x-link="http://www.w3.org/1999/xlink"/>
Dravidian answered 6/5, 2010 at 11:25 Comment(1)
I go with the inclusion in the top element, as I will potentially use this more than one place in the xls.Vexillum
P
4

While @Mads-Hansen has provided a good answer, it is good to know that there is an alternative way to reference names that are in a namespace:

In this case, you could also acces the attribute with the following XPath expression:

   DCPType/HTTP/Get/OnlineResource/@*
            [namespace-uri() = 'http://www.w3.org/1999/xlink']
Plumper answered 6/5, 2010 at 13:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.