如何通过Xslt转换来转换xml

时间:2019-12-21 12:08:02

标签: xml xslt

我有xml输出

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="/topic/get-all.xslt"?>
<List>
    <item>
        <id>8541915a-9098-4d10-bf80-5fbc9a5800af</id>
        <name>TestTopfdic4</name>
        <modifiedDate>2019-12-18T12:37:42.718</modifiedDate>
    </item>
    <item>
        <id>55bc34e6-5cd2-436a-9d37-ceb1052187b0</id>
        <name>TestTopfdic4</name>
        <modifiedDate>2019-12-18T12:40:12.948</modifiedDate>
    </item>
    <item>
        <id>2fee9ce3-1595-4c56-9833-cda03642ad05</id>
        <name>TestTopfdic4</name>
        <modifiedDate>2019-12-18T12:42:15.385</modifiedDate>
    </item>
</List>

并尝试通过xslt将其压缩为html,我尝试选择每个项目并分开处理

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:template match="/*">
        <html>
            <body>
                <table align="center">
                    <thead>
                        <th>Id</th>
                        <th>Name</th>
                        <th>modified date</th>
                    </thead>
                    <tbody>
                        <xsl:for-each select="List">
                            <tr>
                                <td><xsl:value-of select="item.id"/></td>
                                <td><xsl:value-of select="item.name"/></td>
                                <td><xsl:value-of select="item.modifiedDate"/></td>
                            </tr>
                        </xsl:for-each>
                    </tbody>

                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

但是输出为空,我在做什么错呢?请问您能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您的语法不是XPath语法。试试:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:template match="/List">
        <html>
            <body>
                <table align="center">
                    <thead>
                        <th>Id</th>
                        <th>Name</th>
                        <th>modified date</th>
                    </thead>
                    <tbody>
                        <xsl:for-each select="item">
                            <tr>
                                <td><xsl:value-of select="id"/></td>
                                <td><xsl:value-of select="name"/></td>
                                <td><xsl:value-of select="modifiedDate"/></td>
                            </tr>
                        </xsl:for-each>
                    </tbody>

                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:0)

这里有两个错误。首先,<xsl:for-each select="List"/>遍历多个List元素。您只有一个List元素,并且您正在尝试遍历其子元素:即<xsl:for-each select="List/*"/>。但是然后上下文项必须是根(文档)节点,而不是List元素,因此您需要match="/"而不是match="/*"

第二,您使用了“。”而不是“ /”作为路径分隔符:item.id应该为item/id