0

How to transform this XML file:

<file>
  <text ID="201" date="2014-05-04">
    <user_name>user_11</user_name>
    <message> HELLO </message>
  </text>
</file>

into this XML file by using XSLT 1.0:

<doc>
  <user name="user_11">
    <text id="201" date="2014-05-04"> HELLO </text> 
  </user>
</doc>

Also if you have any resources on the subject, please post because I have a lot more of XSLT file to code. thanks

1
  • I have rolled back your question to its original form, otherwise the answers do not make sense. Commented Jul 5, 2014 at 15:50

2 Answers 2

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

<xsl:template match="/">
    <doc>
        <xsl:for-each select="file/text">
            <user name="{user_name}">
                <text id="{@ID}" date="{@date}">
                    <xsl:value-of select="message" />
                </text> 
            </user>
        </xsl:for-each>
    </doc>
</xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

Comments

2

I assume you have a files container in your XML, anyway you are looking for something like this:

<?xml version="1.0" encoding="ISO-8859-1"?>

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

<xsl:template match="/">
  <docs>
    <xsl:for-each select="files/file">
      <xsl:element name="doc">
        <xsl:element name="text">
         <xsl:attribute name="name">
          <xsl:value-of select="text/user_name" />
         </xsl:attribute>  
          <xsl:element name="text">
           <xsl:attribute name="id">
            <xsl:value-of select="text/@ID" />
           </xsl:attribute> 
           <xsl:attribute name="date">
            <xsl:value-of select="text/@date" />
           </xsl:attribute> 
           <xsl:value-of select="text/message" />
          </xsl:element>
        </xsl:element>      
      </xsl:element>       
    </xsl:for-each>
  </docs>
</xsl:template>
</xsl:stylesheet>

2 Comments

XSLT is verbose, but it doesn't need to be that verbose. You can output literal elements by writing them directly to the result tree, and you can use the attribute value template to shorten your code. w3.org/TR/xslt/#section-Creating-Elements-and-Attributes
@michael.hor257k please post your answer, I'd like to see what do you intend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.