简体   繁体   中英

How to convert one XML file into another using XSLT?

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

<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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM