【问题标题】:Sorting multiple XML elements within a node, by attribute按属性对节点内的多个 XML 元素进行排序
【发布时间】:2010-03-10 00:59:03
【问题描述】:

我已经尝试了几个在这里找到的解决方案,但似乎没有一个适用于我正在使用的模型。在我的示例 XML 中,我试图将混杂的章节按正确的顺序排序。

源 XML:

<?xml version="1.0" encoding="utf-8"?>  
<library>  
    <book>  
        <title>A Fascinating Tale</title>  
        <chapter num="4">
            <text>...and rambles to the end.</text>  
        </chapter>  
        <chapter num="2">  
            <text>The hero would...</text>  
        </chapter>  
        <chapter num="3">  
            <text>This went rambling on...</text>  
        </chapter>  
        <chapter num="1">  
            <text>Once upon a time...</text>  
        </chapter>  
    </book>  
</library>  

应该导致:

<?xml version="1.0" encoding="utf-8"?>  
<library>  
    <book>  
        <title>A Fascinating Tale</title>  
        <chapter num="1">  
            <text>Once upon a time...</text>  
        </chapter>  
        <chapter num="2">  
            <text>The hero would...</text>  
        </chapter>  
        <chapter num="3">  
            <text>This went rambling on...</text>  
        </chapter>  
        <chapter num="4">  
            <text>...and rambles to the end.</text>  
        </chapter>  
    </book>  
</library>  

所以从我在这里找到的样式表解决方案中,我无法得到任何工作。我让这太难了吗?看起来应该相当简单。

【问题讨论】:

  • 我认为有些东西已经吃掉了您发布的 XML 示例...
  • 是的,我在每行的开头添加了“4 个空格”,但它似乎不起作用,所以我添加了“反哈希”,以强制它们出现。这是我的第一篇文章,所以我不知道如何解决它。
  • 您需要在普通文本和缩进四文本之间有一个空行。我刚刚解决了这个问题。
  • 谢谢!这样就更有意义了。

标签: xml sorting xslt


【解决方案1】:

Altova XMLSpy 救援:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
    <!-- Identity transform - copies everything that doesn't have an explicit match below -->
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- Special handling for book element. Copy it, then any title and any chapter-->
    <!-- But sort any chapter elements by num attribute -->
    <xsl:template match="book">
        <xsl:copy>
            <xsl:apply-templates select="title"/>
            <xsl:apply-templates select="chapter">
                <xsl:sort select="@num"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

【讨论】:

  • 不是我不喜欢一些 XmlSpy,而是您使用的 XML 编辑器与您的答案有什么关系?
  • 太棒了!这完美地工作。非常感谢。现在我需要蹒跚学步,将此代码与我尝试过的其他示例进行比较,并尝试理解这行得通的地方,以及其他人没有的地方。再次感谢您。
  • @Robert:这就是我看到问题 17 分钟后得到答案的原因。信用到期。
  • 我可能刚刚脱离了循环。我已经有几年没用过 XmlSpy 了;他们一定在其中添加了一些转换构建工具。你的评论对我来说就像“记事本来拯救!”
  • @Robert:还有另一个工具(MapForce)可以生成转换。我只是使用了编辑器和调试器,它们是 XMLSpy 的一部分。
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多