Convert from nested to flattened XML using XSLT

I am trying to accomplish this task in XSLT: Convert XML with nested elements to a less nested XML format.

Convert From:

<example>
 <value>
  aaa
   <value>
    bbb
      <value>
       ccc
      </value>
   </value>
 </value>
</example>

To:

<example>
  <value>aaa</value>
  <value>aaa</value>
  <value>bbb</value>
  <value>bbb</value>
  <value>ccc</value>
  <value>ccc</value>
</example>

I am trying to find a solution, but I only have this:

    <xsl:template match="/">
      <exmaple>
         <xsl:apply-templates/>
      </exmaple>
    </xsl:template>

    <xsl:template match="//value/text()">

     <value><xsl:value-of select="."/></value>
     <value><xsl:value-of select="."/></value>

    </xsl:template>

Result (problem with empty tags):

<exmaple>
<value>
aaa
</value><value>
aaa
</value><value>
bbb
</value><value>
bbb
</value><value>
ccc
</value><value>
ccc
</value><value>
</value><value>
</value><value>
</value><value>
</value>
</exmaple>
+4
source share
2 answers

Try this template with XPath //value/text()[1]:

<xsl:template match="//value/text()[1]">
    <value><xsl:value-of select="." /></value>
    <value><xsl:value-of select="." /></value>
</xsl:template>

The trick is that you need to select the first node text from each <value>, as it text()will return their collection.

+1
source
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes"/>

    <xsl:template match="example">
        <xsl:copy>
            <xsl:apply-templates select=".//value"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="value">
        <xsl:copy>
            <xsl:value-of select="normalize-space(text())"/>
        </xsl:copy>
        <xsl:copy>
            <xsl:value-of select="normalize-space(text())"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
+2
source

Source: https://habr.com/ru/post/1569085/


All Articles