Home > Enterprise >  connect data from different elements of xml file while making xml to xml transformation with xslt
connect data from different elements of xml file while making xml to xml transformation with xslt

Time:01-12

So, I have xml file with structure:

`<root>
    <messages>
        <message id="1005">
            <title>message1</title>
            <text>text1</text1>
        </message>
        <message id="1012">
            <title>message2</title>
            <text>text2</text1>
        </message>
        <message id="13001">
            <title>message3</title>
            <text>text3</text1>
        </message>  
    </messages>
    <data>
        <sender>
            <name>sender1</name>
            <messages>
                <message id="1005" time="12:00"/>
                <message id="1012" time="12:30"/>
            </messages>
        </sender>
        <sender>
            <name>sender2</name>
            <messages>
                <message id="10012" time="2:00"/>
                <message id="13001" time="13:20"/>
            </messages>
        </sender>
    </data>
<root>`

Output I need for each message:

`<Record>
    <Message>
        <MessageID>1005</MessageID>
        <MessageTitle>message1</MessageTitle>
        <time>12:00</time>
        <sender>sender1</sender>
    </message>
</Record>`

I understand what needs to be done to output the id and title from the source file. Problem is I don't know how to make this kind of sql join connection to output time and sender from another element.

CodePudding user response:

Here's a simple way this could be done using a key.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
  
  <xsl:output method="xml" indent="yes"/>
  
  <xsl:key name="message_key" match="message[ancestor::data]" use="@id"/>

  <xsl:template match="/">
    <Records>
      <xsl:apply-templates select="root/messages/message"/>
    </Records>
  </xsl:template>
  
  <xsl:template match="message">
    <Record>
      <Message>
        <MessageID><xsl:value-of select="@id"/></MessageID>
        <MessageTitle><xsl:value-of select="title"/></MessageTitle>
        <time><xsl:value-of select="key('message_key',@id)/@time"/></time>
        <sender><xsl:value-of select="key('message_key',@id)/../../name"/></sender>
      </Message>
    </Record>
  </xsl:template>
  
</xsl:stylesheet>

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

  • Related