Ingvar Petrov
Ingvar Petrov

Reputation: 23

XSLT convert child node text to the parent's attribute

I'm trying to use XSL to transform my XML document so that text values of certain child nodes become attributes of their parents.

Here's what I have:

<?xml version="1.0" encoding="UTF-8"?>
<property_data>
  <property>
    <property_descriptions>
      <property_description>
        <type>property</type>
        <description>property 1000 description</description>
      </property_description>
      <property_description>
        <type>rate</type>
        <description>text rate description</description>
      </property_description>
    </property_descriptions>
    <property_attributes>
      <property_id>1000</property_id>
    </property_attributes>
  </property>
    <property>
...
  </property>
</property_data>

And here's what I'm trying to achieve:

 <?xml version="1.0" encoding="UTF-8"?>
 <property_data>
  <property>
    <property_descriptions>
      <property_description type="property">property 1000 description</property_description>
      <property_description type="rate">text rate description</property_descriptions>
    <property_attributes>
      <property_id>1000</property_id>
    </property_attributes>
  </property>
    <property>
...
  </property>
</property_data>

I'm stuck with the part where I need to select child's value.

EDIT: Following michael.hor257k advice I was able to get the following .xsl that does the job:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="1.0">

    <!--Identity Transform.-->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="property_description">
        <property_description type="{type}">
            <xsl:value-of select="description"/>
        </property_description>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 0

Views: 579

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

This, together with the identity transform template, should provide the expected result:

<xsl:template match="property_description">
    <property_description type="{type}">
        <xsl:value-of select="description"/>
    </property_description>
</xsl:template>

Upvotes: 1

Related Questions