【问题标题】:How to select elements by part of their name in XSL/XPath?如何在 XSL/XPath 中按部分名称选择元素?
【发布时间】:2012-03-05 05:56:45
【问题描述】:

如何使用应用模板仅选择以特定模式结尾的名称(而非值)元素?假设下面的xml...

<report>
  <report_item>
    <report_created_on/>
    <report_cross_ref/>
    <monthly_adj/>
    <quarterly_adj/>
    <ytd_adj/>
  </report_item>
  <report_item>
   ....
  </report_item>
</report>

我想在后代元素以“adj”结尾的所有&lt;report_item&gt; 实例上使用&lt;xsl:apply-templates&gt;,因此,在这种情况下,只会选择monthly_adj、quaterly_adj 和ytd_adj 并将其与模板一起应用。

<xsl:template match="report">
   <xsl:apply-templates select="report_item/(elements ending with 'adj')"/>
</xsl:template>

【问题讨论】:

    标签: xml regex xslt transform


    【解决方案1】:

    稍微简洁的解决方案(仅限 XSLT 2.0+):

    <xsl:apply-templates select="report_item/*[matches(name(),'adj$')]"/>
    

    这是一个自我测试,以证明它有效。 (在撒克逊测试)。

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:fn="http://www.w3.org/2005/xpath-functions" 
                    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
                    exclude-result-prefixes="xs fn">
     <xsl:output method="xml" indent="yes" encoding="utf-8" />
     <xsl:variable name="report-data">
      <report>
       <report_item>
         <report_created_on/>
         <report_cross_ref/>
         <monthly_adj>Jan</monthly_adj>
         <quarterly_adj>Q1</quarterly_adj>
         <ytd_adj>2012</ytd_adj>
       </report_item>
      </report>
     </xsl:variable>
     <xsl:template match="/" name="main">
      <reports-ending-with-adj>
       <xsl:element name="using-regex">
        <xsl:apply-templates select="$report-data//report_item/*[fn:matches(name(),'adj$')]"/> 
       </xsl:element>
       <xsl:element name="using-ends-with-function">
        <xsl:apply-templates select="$report-data//report_item/*[fn:ends-with(name(), 'adj')]"/>
       </xsl:element>
      </reports-ending-with-adj>
     </xsl:template>
    </xsl:stylesheet>
    

    【讨论】:

    • match 为我工作。但是我有一个问题:xsltransform.net/pPzifp5/3(我想以mOrder 的顺序来说明我想显示哪个li 第一、第二、第三...)谢谢。
    • 或类似这样的:xsltransform.net/pPzifp5/4(我希望显示父 LI 和子 LI,但每次迭代和复制都会相乘。我不想显示空的 LI,只显示如果有文字。)感谢您的帮助
    • 发布一个问题,它会得到回答。
    【解决方案2】:

    我认为正则表达式语法在这种情况下不可用,即使在 XSLT 2.0 中也是如此。但在这种情况下你不需要它。

    <xsl:apply-templates select="report_item/*[ends-with(name(), 'adj')]"/>
    

    * 匹配任何节点

    [pred] 对选择器(在本例中为 *)执行节点测试(其中 pred 是在所选节点的上下文中评估的谓词)

    name() 返回元素的标签名称(为此目的,应等同于local-name)。

    ends-with() 是一个内置的 XPath 字符串函数。

    【讨论】:

    • 新的堆栈溢出世界纪录....有史以来最快的答案,大声笑,你是对的,不是正则表达式,只是简单的ends with 就足够了,谢谢。
    • 很高兴为您提供帮助 :) 我更新了标题以更好地匹配问题。
    • 请注意,end-with not 在 xslt 1.0 中可用。请参阅 use ends with in XSLT v1.0 了解 1.0 解决方法。
    猜你喜欢
    • 2011-03-18
    • 2011-11-06
    • 1970-01-01
    • 2022-11-14
    • 2012-01-06
    • 2012-07-19
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多