草庐IT

xml - XSLT 将结果分成 3 组

coder 2024-06-24 原文

网络应用程序正在为我提供 XML 提要,我无法更改。我想要做的是将这个 XML 提要分成几个无序列表。我正在尝试使用下面的 XSLT 执行此操作。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >    
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" encoding="utf-8" />
  <xsl:param name="html-content-type" />
  <xsl:template match="/NavigationTree">
    <xsl:if test="count(//Page) > 0">
      <ul>
        <xsl:apply-templates select="Page">
        </xsl:apply-templates>
      </ul>
    </xsl:if>
  </xsl:template>

  <xsl:template match="//Page">    
    <li class="{position() mod 3}">
      <xsl:text disable-output-escaping="yes"><![CDATA[»&nbsp;]]></xsl:text>
      <a>
        <xsl:attribute name="href">
          <xsl:value-of select="@FriendlyHref" disable-output-escaping="yes"/>
        </xsl:attribute>
        <xsl:value-of select="@MenuText" disable-output-escaping="no"/>
      </a>
    </li>

    <xsl:if test="position() mod 3 = 0">
      <xsl:if test="position() &lt; count(//Page)">
        <!--Don't know if this is the correct approach, but when the position is 3 and there are more items following
        I want to create an new unordered list-->
      </xsl:if>      
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

使用上面的 XSLT,我能够将 XML 转换为一个包含 6 个项目的无序列表(假设总是有 6 个项目)。类似于下面的例子;

<ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
    <li>Item4</li>
    <li>Item5</li>
    <li>Item6</li>
</ul>

上面的例子是我现在得到的结果。但是想要的结果是这样的;

<ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
</ul>
<ul>
    <li>Item4</li>
    <li>Item5</li>
    <li>Item6</li>
</ul>

编辑 - 示例 XML 输入

<NavigationTree>
    <Settings>
        <!--Snipped data-->
    </Settings>
    <Page ID="5" AreaID="1" MenuText="Bestellen" MouseOver="" Href="Default.aspx?ID=5" FriendlyHref="/nl-nl/klantenservice/bestellen.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="1" LastInLevel="False" InPath="False" ChildCount="0" class="L2" Active="False" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
    <Page ID="6" AreaID="1" MenuText="Betalen" MouseOver="" Href="Default.aspx?ID=6" FriendlyHref="/nl-nl/klantenservice/betalen.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="2" LastInLevel="False" InPath="True" ChildCount="0" class="L2_Active" Active="True" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
    <Page ID="7" AreaID="1" MenuText="Retourneren" MouseOver="" Href="Default.aspx?ID=7" FriendlyHref="/nl-nl/klantenservice/retourneren.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="3" LastInLevel="False" InPath="False" ChildCount="0" class="L2" Active="False" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
    <Page ID="8" AreaID="1" MenuText="Garantie" MouseOver="" Href="Default.aspx?ID=8" FriendlyHref="/nl-nl/klantenservice/garantie.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="4" LastInLevel="False" InPath="False" ChildCount="0" class="L2" Active="False" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
    <Page ID="9" AreaID="1" MenuText="Faq" MouseOver="" Href="Default.aspx?ID=9" FriendlyHref="/nl-nl/klantenservice/veel-gestelde-vragen.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="5" LastInLevel="False" InPath="False" ChildCount="0" class="L2" Active="False" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
    <Page ID="10" AreaID="1" MenuText="Contact" MouseOver="" Href="Default.aspx?ID=10" FriendlyHref="/nl-nl/klantenservice/contact.aspx" Image="" ImageActive="" ImageMouseOver="" Title="" Allowclick="True" ShowInSitemap="True" ShowInLegend="True" AbsoluteLevel="2" RelativeLevel="2" Sort="6" LastInLevel="True" InPath="False" ChildCount="0" class="L2" Active="False" IsPagePasswordProtected="False" IsPageUserProtected="False" CanAccessPasswordProtectedPage="False" CanAccessUserProtectedPage="True"/>
</NavigationTree>

如您所见,我总是希望以 3 项为一组输出。使用 XSLT 可以输出这种 html 吗?如果是,我该怎么做?欢迎任何帮助!

最佳答案

我。 XSLT 1.0 .

这是一个简短的参数化解决方案,展示了如何将兄弟元素拆分为预定义大小的组。 没有使用显式条件 XSLT 指令:

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

 <xsl:param name="pGroupSize" select="3"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <nums>
   <xsl:apply-templates select=
       "num[position() mod $pGroupSize = 1]"/>
  </nums>
 </xsl:template>

 <xsl:template match="num">
  <group>
   <xsl:copy-of select=
    ".|following-sibling::*
              [not(position() > $pGroupSize -1)]"/>
  </group>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于以下 XML 文档时:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

产生了想要的、正确的结果:

<nums>
   <group>
      <num>01</num>
      <num>02</num>
      <num>03</num>
   </group>
   <group>
      <num>04</num>
      <num>05</num>
      <num>06</num>
   </group>
   <group>
      <num>07</num>
      <num>08</num>
      <num>09</num>
   </group>
   <group>
      <num>10</num>
   </group>
</nums>

二。 XSLT 2.0

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pGroupSize" select="3"/>

 <xsl:template match="/*">
     <nums>
       <xsl:for-each-group select="*"
            group-by="(position() -1) idiv $pGroupSize">
         <group>
          <xsl:sequence select="current-group()"/>
         </group>
       </xsl:for-each-group>
     </nums>
 </xsl:template>
</xsl:stylesheet>

当这个转换应用于相同的 XML 文档时(如上),产生相同的正确结果:

<nums>
   <group>
      <num>01</num>
      <num>02</num>
      <num>03</num>
   </group>
   <group>
      <num>04</num>
      <num>05</num>
      <num>06</num>
   </group>
   <group>
      <num>07</num>
      <num>08</num>
      <num>09</num>
   </group>
   <group>
      <num>10</num>
   </group>
</nums>

解释:

  1. 使用<xsl:for-each-group>其中所选节点按其所属组的序号分组。

  2. 标准 XSLT 2.0 函数的使用 current-group() .

关于xml - XSLT 将结果分成 3 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7316260/

有关xml - XSLT 将结果分成 3 组的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. 报告回顾丨模型进化狂飙,DetectGPT能否识别最新模型生成结果? - 2

    导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri

  3. ruby-on-rails - 如何在 Rails 3 中禁用 XML 解析 - 2

    我想禁用HTTP参数的自动XML解析。但我发现命令仅适用于Rails2.x,它们都不适用于3.0:config.action_controller.param_parsers.deleteMime::XML(application.rb)ActionController::Base.param_parsers.deleteMime::XMLRails3.0中的等价物是什么? 最佳答案 根据CVE-2013-0156的最新安全公告你可以将它用于Rails3.0。3.1和3.2ActionDispatch::ParamsParser::

  4. ruby - 如何使用 Nokogiri::XML::Builder 生成动态标签? - 2

    我正在遍历数组中的一组标签名称,我想使用构建器打印每个标签名称,而不是求助于“我认为:builder=Nokogiri::XML::Builder.newdo|xml|fortagintagsxml.tag!tag,somevalendend会这样做,但它只是创建名称为“tag”的标签,并将标签变量作为元素的文本值。有人可以帮忙吗?这个看起来应该比较简单,我刚刚在搜索引擎上找不到答案。我可能没有以正确的方式提问。 最佳答案 尝试以下操作。如果我没记错的话,我添加了一个根节点,因为Nokogiri需要一个。builder=Nokogi

  5. ruby - 如何让 Nokogiri 解析并返回 XML 文档? - 2

    这是一些奇怪的例子:#!/usr/bin/rubyrequire'rubygems'require'open-uri'require'nokogiri'print"withoutread:",Nokogiri(open('http://weblog.rubyonrails.org/')).class,"\n"print"withread:",Nokogiri(open('http://weblog.rubyonrails.org/').read).class,"\n"运行此返回:withoutread:Nokogiri::XML::Documentwithread:Nokogiri::

  6. ruby - gem 推送结果为 "package metadata is missing" - 2

    我正在尝试将我更新的gem推送到ruby​​gems.com并得到以下结果。~/dev/V2/V2GPTI(master)$gembuildv2gpti.gemspecSuccessfullybuiltRubyGemName:v2gptiVersion:0.2File:v2gpti-0.2-universal-darwin-13.gem~/dev/V2/V2GPTI(master)$gempushv2gpti.gemspecERROR:Whileexecutinggem...(Gem::Package::FormatError)packagemetadataismissinginv2g

  7. ruby - 模式加载时出现 Nokogiri::XML::Schema SyntaxError - 2

    我正在尝试加载SAML协议(protocol)架构(具体来说:https://www.oasis-open.org/committees/download.php/3407/oasis-sstc-saml-schema-protocol-1.1.xsd),但在执行此操作之后:schema=Nokogiri::XML::Schema(File.read('saml11_schema.xsd'))我得到这个输出:Nokogiri::XML::SyntaxErrorException:Element'{http://www.w3.org/2001/XMLSchema}element',att

  8. ruby - 猴子修补 float 中缀运算符产生意想不到的结果 - 2

    重新定义Float#/似乎没有效果:classFloatdef/(other)"magic!"endendputs10.0/2.0#=>5.0但是当另一个中缀运算符Float#*被重新定义时,Float#/突然采用了新的定义:classFloatdef/(other)"magic!"enddef*(other)"spooky"endendputs10.0/2.0#=>"magic!"我很想知道是否有人可以解释这种行为的来源,以及其他人是否得到相同的结果。ruby:ruby2.0.0p353(2013-11-22)[x64-mingw32]要快速确认错误,请运行thisscript.

  9. ruby-on-rails - 尝试编辑时,Rails form_for 结果为 POST 而不是 PUT - 2

    我正在使用Rails4并遇到以下错误。RoutingErrorNoroutematches[POST]"/logs/1/meals/13/edit我正在使用:meal传递模型对象的form_for,并且编辑页面正确呈现。但是,Rails似乎并没有检查膳食对象是否已经保存,因此它一直尝试将表单发送到#create操作并尝试发出POST请求,而不是将表单发送到更新操作并进行当我点击提交时一个PUT请求。我如何让form_for识别我正在尝试更新现有对象并且需要PUT而不是POST?其他一切正常,我已经运行了所有迁移。我是Rails的新手,几乎一整天都在尝试自己解决这个问题。请帮忙!请注意,

  10. ruby - 为什么会.is_a?和 .class 给出相互矛盾的结果? - 2

    我有三个属于同一个类的对象。一个是通过Item.new创建的,另外两个是从数据库(Mongoid)中提取的。我将这些对象中的一个/任何一个传递给另一个方法,并通过is_a?检查该方法中的类型:definitialize(item,attrs=nil,options=nil)super(attrs,options)raise'invaliditemobject'unlessitem.is_a?(Item)好吧,这次加薪被击中了。所以我在Rails控制台中检查类、is_a和instance_of。我得到相互矛盾的结果。为什么它们有相同的class但只有其中一个是那个class的instan

随机推荐