【问题标题】:Setting the order of XML attributes via XSLT? [duplicate]通过 XSLT 设置 XML 属性的顺序? [复制]
【发布时间】:2016-08-31 13:46:28
【问题描述】:

我有使用 XSLT 解析的 XML 格式的 HTML。我的 HTML 如下所示:

<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<img height=""  width="' src="google.gif?<>" />
</body>
</html>

XSLT 解析后如下所示:

 <html>
    <head>
    <meta charset="utf-8" />
    <title>Test</title>
    </head>
    <body>
    <img height="" src="google.gif?<>" width=""/>
    </body>
    </html>

我希望 @src&lt;img height="" width="" src="google.gif?&lt;&gt;" /&gt; 一样作为最后一个属性,但默认情况下,属性按字母顺序排序。我无法使用&lt;xsl:sort&gt; 来做到这一点。

【问题讨论】:

标签: java html xml xslt


【解决方案1】:

XSLT 生成符合 XDM 数据模型的结果树作为输出,并且在 XDM 模型中,属性是无序的。由于它们没有顺序,因此 XSLT 样式表指令无法控制顺序。

控制顺序的唯一机会出现在序列化期间,当结果树中的无序属性节点在词法 XML 输出中转换为 name="value" 对的有序序列时。 XSLT(任何版本)中可用的标准序列化属性不提供任何控制它的方法。然而,撒克逊人有一个扩展属性saxon:attribute-order - 请参阅

http://www.saxonica.com/documentation/index.html#!extensions/output-extras/serialization-parameters

【讨论】:

    【解决方案2】:

    输入 HTML(带有格式):

    <html>
    <head>
        <meta charset="utf-8" />
        <title>Test</title>
    </head>
        <body>
            <img height="13" width="12" src="google.gif?" id="id1"/>
        </body>
    </html>
    

    XSLT:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    
    <xsl:template match="@*|node()">
        <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
    </xsl:template>
    
    <xsl:template match="img">
        <xsl:copy>
            <xsl:for-each select="@*[not(name()='src')]">
                <xsl:sort select="name()"/>
                <xsl:attribute name="{name()}">
                    <xsl:value-of select="."/>
                </xsl:attribute>
            </xsl:for-each>
            <xsl:apply-templates select="@*[name()='src']"/>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    结果:

    <html>
    <head>
      <meta charset="utf-8"/>
      <title>Test</title>
    </head>
    <body>
      <img height="13" id="id1" width="12" src="google.gif?"/>
    </body>
    </html>
    

    【讨论】:

    • 嗨,我想要结果为 Test 我总是希望@src 在最后。
    • @user3287034,根据kjhughes的建议编辑了我的答案,属性可以是任何顺序,但仅当其他一些脚本语言(不支持xpath)正在访问或处理输入xml时,对于当时的查找替换过程,这些属性的位置可能会有所帮助。
    【解决方案3】:

    除了&lt;img height="" width="' src="google.gif?&lt;&gt;" /&gt; 的格式不是commented by Martin Honnen...

    Attribute order is insignificantXML Recommendation

    请注意,开始标签中属性规范的顺序或 空元素标签不重要。

    因此,XSLT 没有提供约束属性排序的方法。

    如果您拒绝接受此建议以忽略属性排序,请参阅Martin Honnen's suggestions regarding how to control attribute ordering output 以了解XSLT attribute ordering 上的较早问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多