给定以下 xml 片段:
<Problems>
<Problem>
<File>file1</File>
<Description>desc1</Description>
</Problem>
<Problem>
<File>file1</File>
<Description>desc2</Description>
</Problem>
<Problem>
<File>file2</File>
<Description>desc1</Description>
</Problem>
</Problems>
我需要制作类似的东西
<html>
<body>
<h1>file1</h1>
<p>des1</p>
<p>desc2</p>
<h1>file2</h1>
<p>des1</p>
</body>
</html>
我试过使用 key ,比如
<xsl:key name="files" match="Problem" use="File"/>
但我真的不明白如何将它带到下一步,或者这是否是正确的方法。
最佳答案
这个解决方案比 Richard 提出的解决方案更简单、更高效,同时更通用:
这个转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- -->
<xsl:key name="kFileByVal" match="File"
use="." />
<!-- -->
<xsl:key name="kDescByFile" match="Description"
use="../File"/>
<!-- -->
<xsl:template match="/*">
<html>
<body>
<xsl:for-each select=
"*/File[generate-id()
=
generate-id(key('kFileByVal',.)[1])]">
<h1><xsl:value-of select="."/></h1>
<xsl:for-each select="key('kDescByFile', .)">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<Problems>
<Problem>
<File>file1</File>
<Description>desc1</Description>
</Problem>
<Problem>
<File>file1</File>
<Description>desc2</Description>
</Problem>
<Problem>
<File>file2</File>
<Description>desc1</Description>
</Problem>
</Problems>
产生想要的结果:
<html>
<body>
<h1>file1</h1>
<p>desc1</p>
<p>desc2</p>
<h1>file2</h1>
<p>desc1</p>
</body>
</html>
请注意第一个 <xsl:key>
的简单匹配模式以及如何使用第二个 <xsl:key>
,我们找到所有“Description
”元素,这些元素是具有给定值的“File
”元素的 sibling 。
我们本可以使用更多模板而不是 <xsl:for-each>
拉式处理,但这是一个非常简单的案例,该解决方案真正受益于更短、更紧凑和更易读的代码。
另请注意,在 XSLT 2.0 中人们通常会使用 <xsl:for-each-group>
指令 而不是Muenchian method .
关于xml - 不同的元素和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/399204/