Algy Taylor February 2016

Get value of an attribute, where you don't know the name

Say if I have some XML with a line such as:

<machine center="10" left="25" right="162" />

and, using XSLT, I want to turn that in to something like:

<measurement type="center">10</measurement>
<measurement type="left">25</measurement>
<measurement type="right">162</measurement>

How do I do that? At the moment I have the following, but am missing one crucial part:

<measurement>
  <xsl:for-each select="@">
    <xsl:attribute name="type">
      <xsl:value-of name="name()">
    </xsl:attribute name="type">
    <xsl:value-of name="[WHAT_GOES_HERE?]" />
  </xsl:for-each>
</measurement>

Answers


michael.hor257k February 2016

Try it this way;

<xsl:template match="machine">
    <xsl:for-each select="@*">
        <measurement type="{name()}">
            <xsl:value-of select="." />
        </measurement>
    </xsl:for-each>
</xsl:template>


zx485 February 2016

A way to achieve this is:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:template match="machine">
        <xsl:for-each select="@*">
            <xsl:element name="measurement">
                <xsl:attribute name="type">
                    <xsl:value-of select="local-name()" />
                </xsl:attribute>
                <xsl:value-of select="." />
            </xsl:element>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


Dimitre Novatchev February 2016

This solution is both: simpler/shorter, avoids <xsl:for-exch> and is fully in the spirit of XSLT:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="machine">
    <xsl:apply-templates select="@*"/>
  </xsl:template>
  <xsl:template match="machine/@*">
   <measurement type="{name()}"><xsl:value-of select="."/></measurement>
  </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<machine center="10" left="25" right="162" />

the wanted, correct result is produced:

<measurement type="center">10</measurement>
<measurement type="left">25</measurement>
<measurement type="right">162</measurement>

Post Status

Asked in February 2016
Viewed 2,188 times
Voted 11
Answered 3 times

Search




Leave an answer