RoRu
RoRu

Reputation: 15

XSLT Transformation: move content of nodes into one node

I have following XML:

<EAD:c>
  <EAD:accessrestrict type="aaa">
    <EAD:p>
      value1
    </EAD:p>
  </EAD:accessrestrict>
  <EAD:accessrestrict type="bbb">
    <EAD:p>
      value2
    </EAD:p>
  </EAD:accessrestrict>
</EAD:c>

there are multiple <EAD:c> nodes, and not all of them necessarily have <EAD:accessrestrict type="aaa"> or <EAD:accessrestrict type="bbb">

outcome after transformation should be:

<EAD:c>
  <EAD:accessrestrict>
    <EAD:p>
      value1; value2;
    </EAD:p>
  </EAD:accessrestrict>
</EAD:c>

i have no idea how to do this, your help is much appreciated!

Upvotes: 0

Views: 48

Answers (1)

Sebastien
Sebastien

Reputation: 2714

You can do it like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:EAD="http://www.somens.com"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="EAD:c">
      <xsl:copy>
        <EAD:accessrestrict>
          <EAD:p>
            <xsl:for-each select="EAD:accessrestrict/EAD:p">
              <xsl:value-of select="normalize-space(.)"/>
              <xsl:if test="position()!=last()"><xsl:text>; </xsl:text></xsl:if>
              <xsl:if test="position()=last()"><xsl:text>;</xsl:text></xsl:if>
            </xsl:for-each>
          </EAD:p>
        </EAD:accessrestrict>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

See it working here : https://xsltfiddle.liberty-development.net/gVhDDz1

Upvotes: 1

Related Questions