【问题标题】:XSLT sorting - how to sort AND copy the whole input as sorted outputXSLT 排序 - 如何排序和复制整个输入作为排序输出
【发布时间】:2014-06-30 05:49:14
【问题描述】:

我正在尝试使用 XSLT 转换对 XML 文件进行排序,但它没有达到我想要的效果。我想按 loc 元素按字典顺序对 XML 进行排序。

这是我的原始 XML:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>url3</loc>
    </url>
    <url>
        <loc>url2</loc>
    </url>
    <url>
        <loc>url1</loc>
    </url>
</urlset>

这是 xslt:

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

    <xsl:output method="xml" encoding="utf-8" indent="yes"
        version="1.0" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="urlset">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:apply-templates select="url">
                <xsl:sort select="loc" data-type="text" order="ascending" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

我想看看这个输出:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>url1</loc>
    </url>
    <url>
        <loc>url2</loc>
    </url>
    <url>
        <loc>url3</loc>
    </url>
</urlset>

我尝试关注这个问题,但无法正常工作。

How to sort a subelement

上面的 XSLT 只是复制原始 xml 而不进行任何排序,仅此而已。有人可以帮助我吗?如何对loc 标签进行排序?

【问题讨论】:

    标签: xml sorting xslt xpath xslt-grouping


    【解决方案1】:

    这里的问题不是排序,而是选择/匹配它们自己的命名空间中的节点。这个模板:

    <xsl:template match="urlset">
    

    不做任何事情,因为urlset 元素及其所有后代都在“http://www.sitemaps.org/schemas/sitemap/0.9”命名空间中。您需要在样式表中声明此命名空间,为其分配前缀并在寻址节点时使用该前缀:

    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9">
    
    <xsl:output method="xml" encoding="utf-8" indent="yes" version="1.0" />
    
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="sm:urlset">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:apply-templates select="sm:url">
                <xsl:sort select="sm:loc" data-type="text" order="ascending" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

    • 非常感谢。我已经为此苦苦挣扎了一段时间。是的,问题是缺少命名空间!完美运行。
    猜你喜欢
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多