xml - 不同的元素和分组

标签 xml xslt xpath

给定以下 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/

相关文章:

java - 我的 NavigationDrawer 中的 TextView 文本垂直剪切

java - .xsl 文件不会通过浏览器从 tomcat7 下载

java - XPath//*[@href] 不仅仅抓取链接

xml - 从多个 xml 文件中提取节点

android - XML 渲染错误 Android 预览 N

java - 如何在 Spring 测试期间创建 CrudRepository 接口(interface)的实例?

java - 如何使用 Java 中的 xslt 从纯文本中读取所有数据?

c++ - BSTR bstrRtf = 0xcccccccccccccccc <Bad Ptr> 调试 ( = CXX0030 : Error: expression cannot be evaluated)

php - 选择所有元素直到 - XPath

C# 解析以下 XML,不确定如何