【问题标题】:XSLT Options for "flipping" inner and outer XML用于“翻转”内部和外部 XML 的 XSLT 选项
【发布时间】:2021-09-29 07:09:12
【问题描述】:

我正在评估 XSLT 操作(1.0 和 2.0)是否可以实现以下转换:

原始 XML:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="suiteOne">
      <testcase name="testOne" />
      <testcase name="testTwo" />
      <testcase name="testThree" />
   </testsuite>
   <testsuite name="suiteTwo">
      <testcase name="testFour" />
      <testcase name="testOne">
         <failure message="it failed">Stuff happened oh no oh geez</failure>
      </testcase>
   </testsuite>
</testsuites>

转换后的xml:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="testOne">
      <testcase name="suiteOne" />
      <testcase name="suiteTwo">
         <failure message="it failed">Stuff happened oh no oh geez</failure>
      </testcase>
   </testsuite>
   <testsuite name="testTwo">
      <testcase name="suiteOne" />
   </testsuite>
   <testsuite name="testThree">
      <testcase name="suiteOne" />
   </testsuite>
   <testsuite name="testFour">
      <testcase name="suiteTwo" />
   </testsuite>
</testsuites>

基本上,我需要在维护关系的同时“交换”内部和外部 xml。这在许多语言中是非常可行的,我可以遍历原始 xml 并跟踪我已经遇到的内容(通过字典或类似的东西),但是对于 XLST,我不确定它可能是多么微不足道或复杂.任何建议表示赞赏。

【问题讨论】:

  • 我尝试格式化输入 XML,但 此 XML 无效 - 缺少一些结束元素。如果没有正确格式化的输入和输出 XML - 以及将它们从一个转换到另一个的清晰算法 - 这个问题是无法回答的。至少阅读HowToAsk 并创建minimal reproducible example 以尝试解决此问题。
  • 这很尴尬。我相信我已经使它有效。

标签: xml xslt


【解决方案1】:

这似乎基本上是一个带有扭曲的分组问题。我认为这是您可以查看的一种方式:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/testsuites">
    <xsl:copy>
        <xsl:for-each-group select="testsuite/testcase" group-by="@name">
            <testsuite name="{@name}">
                <xsl:for-each select="current-group()">
                    <testcase name="{../@name}">
                        <xsl:copy-of select="*"/>
                    </testcase>
                </xsl:for-each> 
            </testsuite>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

演示https://xsltfiddle.liberty-development.net/pNEj9dz/2

【讨论】:

  • 谢谢!看起来我有很多东西要了解 XSLT 的可能性:)。我需要花时间来完全吸收这个,但这正是我想要的。
  • 重读后,我想我可能过于复杂了。看看简化版是否适合您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
相关资源
最近更新 更多