微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用xslt保留xml元素的数据位置

如何解决如何使用xslt保留xml元素的数据位置

|| 我们正在转换类似以下xml的内容
<collection>
    <availableLocation>NY</availableLocation>
    <cd>
        fight for your mind
    </cd>
    <cd>
        Electric Ladyland
    </cd>
    <availableLocation>NJ</availableLocation>
</collection>
使用以下xslt
<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
<xsl:output method=\"html\"/>
<xsl:template match=\"/\">
    <html>
        <body>

                 <xsl:apply-templates select=\"collection/availableLocation\"/>
                <xsl:apply-templates select=\"collection/cd\"/>

        </body>
    </html>
</xsl:template>
<xsl:template match=\"availableLocation\">
    <h3>
        <xsl:value-of select=\".\"/>
    </h3>
</xsl:template>
<xsl:template match=\"cd\">
    <xsl:value-of select=\".\"/><br/>
</xsl:template>


</xsl:stylesheet>
输出为:
NY

NJ

fight for your mind 
Electric Ladyland 
我们希望保留xml中的顺序。我们希望输出如下:
NY

fight for your mind 
Electric Ladyland 

NJ
有什么办法吗?请评论/建议。 我通过做这些改变找到了解决方
            <xsl:for-each select=\"collection\">

                <xsl:apply-templates select=\".\"/>

                </xsl:for-each>

    </body>
请让我们知道是否有更好的解决方案。 提前致谢     

解决方法

        
<xsl:apply-templates select=\"collection/availableLocation|collection/cd\"/>
    ,        最简单的解决方案之一甚至不需要明确的
<xsl:apply-templates>
<xsl:stylesheet version=\"1.0\"
 xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
 <xsl:output omit-xml-declaration=\"yes\" indent=\"yes\"/>
 <xsl:strip-space elements=\"*\"/>

 <xsl:template match=\"text()\">
  <xsl:value-of select=\"normalize-space()\"/>
  <xsl:text>&#xA;</xsl:text>
 </xsl:template>
</xsl:stylesheet>
当应用于提供的XML文档时:
<collection>
    <availableLocation>NY</availableLocation>
    <cd>
      Fight for your mind
    </cd>
    <cd>
      Electric Ladyland
    </cd>
    <availableLocation>NJ</availableLocation>
</collection>
所需的正确结果产生了:
NY
Fight for your mind
Electric Ladyland
NJ
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。