Alp
Alp

Reputation: 29739

XPath select nodes multiple times dependent on attributes for XSL transformation

I have a node like this one:

<foo my:first="yes" my:second="no">text</foo>

I need an XPath query or XSLT function which selects each node with attributes in the "my" namespace. But if an element has multiple "my" attributes, the element needs to be selected multiple times.

Currently I have this:

<xsl:template match="//*[@my:*]">
  <bar>
    <xsl:variable name="attributeName" select="local-name(./@my:*)" />
    <xsl:variable name="attributeValue" select="./@my:*" />
    <xsl:attribute name="name">
      <xsl:value-of select="$attributeName" />
    </xsl:attribute>
    <xsl:attribute name="value">
      <xsl:value-of select="$attributeValue" />
    </xsl:attribute>
    <xsl:value-of select="." />
  <bar>
</xsl:template>

And naturally, it only supports single "my" attributes, which results in a transformation like this:

<bar name="attr_in_my_namespace" value="value_of_that_attr">text</bar>

If I try this with the node I presented in the beginning, I get the following error:

A sequence of more than one item is not allowed as the first argument of
  local-name() (@my:first, @my:second) 

So, the expected result would be:

<bar name="first" value="yes">text</bar>
<bar name="second" value="no">text</bar>

How can I achieve that?

Upvotes: 0

Views: 1012

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167581

It looks to me as if you simply want to process the attribute nodes e.g.

<xsl:template match="*/@my:*">
  <bar name="{local-name()}" value="{.}">
    <xsl:value-of select=".."/>
  </bar>
</xsl:template>

and then

<xsl:template match="*[@my:*]">
  <xsl:apply-templates select="@my:*"/>
</xsl:template>

Upvotes: 2

Related Questions