【问题标题】:Displaying XML nodes with XSL but keeping the order on XML - With multiple namespaces使用 XSL 显示 XML 节点但保持 XML 上的顺序 - 具有多个命名空间
【发布时间】:2015-08-05 02:22:07
【问题描述】:

我有以下多命名空间 XML 文件:objects.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="objects.xsl"?>
<objects
    xmlns:objA="http://www.mywebsite.com/objectA"
    xmlns:objB="http://www.mywebsite.com/objectB"
>
    <objA:objectA>
        <objA:attrA1>Instance 1 Value 1</objA:attrA1>
        <objA:attrA2>Instance 1 Value 2</objA:attrA2>
    </objA:objectA>
    <objB:objectB>
        <objB:attrB1>Instance 2 Value 1</objB:attrB1>
        <objB:attrB2>Instance 2 Value 2</objB:attrB2>
    </objB:objectB>
    <objA:objectA>
        <objA:attrA1>Instance 3 Value 1</objA:attrA1>
        <objA:attrA2>Instance 3 Value 2</objA:attrA2>
    </objA:objectA>
    <objB:objectB>
        <objB:attrB1>Instance 4 Value 1</objB:attrB1>
        <objB:attrB2>Instance 4 Value 2</objB:attrB2>
    </objB:objectB>
</objects>

以及以下样式表 XLST 文件:objects.xsl

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:objA="http://www.mywebsite.com/objectA"
    xmlns:objB="http://www.mywebsite.com/objectB"
>

<xsl:template match="/">
  <html>
  <body>

<xsl:for-each select="/objects/objA:objectA">
    (<xsl:value-of select="objA:attrA1"/> |
    <xsl:value-of select="objA:attrA2"/>)<br />
</xsl:for-each>

<xsl:for-each select="/objects/objB:objectB">
    (<xsl:value-of select="objB:attrB1"/> |
    <xsl:value-of select="objB:attrB2"/>)<br />
</xsl:for-each>

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

</xsl:stylesheet>

但结果并不是我想要的,因为我得到了上面的文件:

(Instance 1 Value 1 | Instance 1 Value 2)
(Instance 3 Value 1 | Instance 3 Value 2)
(Instance 2 Value 1 | Instance 2 Value 2)
(Instance 4 Value 1 | Instance 4 Value 2)

这与 XML 文件的顺序不同。我需要和objects.xml一样的顺序:{1, 2, 3, 4}

我知道问题在于 for-each 语句应用于不同的点,但我给出上面的代码来显示我想要的近似值。

我尝试只使用一个 for-each 语句,使用通配符作为命名空间,但似乎命名空间不允许使用通配符。

有什么想法吗?

【问题讨论】:

  • 我需要一些机制以相同的顺序逐步处理XML文件上的每个节点

标签: html xml xslt dom namespaces


【解决方案1】:

试试这个样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <xsl:apply-templates select="/objects/*"/>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="*">
        <xsl:value-of select="concat('(', *[1],' | ', *[2],')')"/>
        <br/>
    </xsl:template>
</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多