mmkd
mmkd

Reputation: 900

XSLT Reformat XML Document

I am looking to make an XSLT that will transform the input XML below:

<?xml version="1.0" encoding="UTF-8"?>
<payload>
    <header>
        <from>From: [email protected]</from>
        <to>To: [email protected]</to>
    </header>

    <email>
        <body>Hello, email body here...</body>
    </email>

    <attachments>
        <attachment>
            <name>log1</name>
        </attachment>

        <attachment>
            <name>log2</name>
        </attachment>

    </attachments>
</payload>

into:

From: [email protected]
To: [email protected]

Hello, email body here...

To: [email protected]
log1


To: [email protected]
log2

Where the To node is repeated after every attachment. There can a number of attachments, not just two.

UPDATE FROM USER

Im pretty new to this, but i tried creating a payload without the header, email, and attachment tags. Then used to arrange them into the correct order but this looks horrible. And is not scalable

Upvotes: 1

Views: 299

Answers (1)

hroptatyr
hroptatyr

Reputation: 4809

How about:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="from|to">
    <xsl:value-of select="text()"/>
    <xsl:text>&#0010;</xsl:text>
  </xsl:template>

  <xsl:template match="body">
    <xsl:text>&#0010;</xsl:text>
    <xsl:value-of select="text()"/>
    <xsl:text>&#0010;</xsl:text>
  </xsl:template>

  <xsl:template match="attachments">
    <xsl:for-each select="attachment">
      <xsl:text>&#0010;&#0010;</xsl:text>
      <xsl:apply-templates select="../../header/to"/>
      <xsl:value-of select="name/text()"/>
      <xsl:text>&#0010;</xsl:text>
    </xsl:for-each>
  </xsl:template>

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

</xsl:stylesheet>

Upvotes: 2

Related Questions