【问题标题】:How to convert one XML file into another using XSLT?如何使用 XSLT 将一个 XML 文件转换为另一个?
【发布时间】:2014-06-29 15:08:17
【问题描述】:

如何转换这个 XML 文件:

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

使用 XSLT 1.0 进入这个 XML 文件:

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

另外,如果您有关于该主题的任何资源,请发布,因为我有更多的 XSLT 文件要编码。谢谢

【问题讨论】:

  • 我已将您的问题回滚到原来的形式,否则答案没有意义。

标签: xml xslt xslt-1.0


【解决方案1】:
<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>

【讨论】:

    【解决方案2】:

    我假设你的XML 中有一个文件容器,无论如何你正在寻找这样的东西:

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

    【讨论】:

    • XSLT 是冗长的,但它不需要是 那个 冗长的。您可以通过将文字元素直接写入结果树来输出它们,并且可以使用 属性值模板 来缩短代码。 w3.org/TR/xslt/#section-Creating-Elements-and-Attributes
    • @michael.hor257k 请发表你的答案,我想看看你的意图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2011-01-17
    相关资源
    最近更新 更多