【问题标题】:XSLT how to test if element has specific name?XSLT如何测试元素是否具有特定名称?
【发布时间】:2021-05-26 14:40:07
【问题描述】:

我想测试一下属性的名字是否包含'description'(不管是description1、2还是3,只要名字里有description)然后在for-each循环中使用这个.如果没有,我不想显示该元素。所以我有一个如下的 XML 结构:

<item>
 <name>Test xslt</name>
 <code>XSLT</code>
 <description>
  <description1>1x stay</description1>
  <description2>1x breakfast</description2>
  <description3>1x diner</description3>
  <description4>1x free late check-out</description1>
  <address>New York 1234AZ</address>
 </description>
</item>

然后我的 XSLT 将是:

<xsl:for-each select="description">
   <xsl:if test=""> (test here if name cointains description)
     <p><xsl:value-of select="." /></p>
   </xsl:if>
</xsl:for-each>

现在它还显示了数组中的元素。有谁知道如何测试元素名称是否包含特定文本然后只显示这些?提前致谢!

编辑:

已经修复了编辑。

【问题讨论】:

  • 在您的示例中,最好使用starts-with(name(), 'description') 而不是在contains() 上浪费CPU 周期。
  • 重新编辑:请发布minimal reproducible example,而不是断章取义的代码sn-ps。

标签: xml xslt


【解决方案1】:

这不需要额外的 xsl:if

  <xsl:for-each select="//*[contains(local-name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

就像@michael.hor257k 在他的评论中建议的那样: 如果你不使用命名空间前缀并且你的“description*”元素总是以“description”开头,你可以通过使用使其表现更好:

  <xsl:for-each select="//*[starts-with(name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

请参阅this answer 以了解name()local-name() 的解释差异

如果您在 xslt 中的上下文是 item-element,您也可以像这样使其工作得更快:

  <xsl:for-each select="descendant::*[starts-with(name(),'description')]">
    <p><xsl:value-of select="." /></p>
  </xsl:for-each>

This site 为您提供有关 xslt 如何工作以及上下文如何变化的更多帮助,即使用 xsl:apply-templatesxsl:for-each

【讨论】:

  • 另见this SO question and answer,其中有一些额外的细节。
  • 很好,这很好用,谢谢!我注意到没有 //*[].你能告诉我它是做什么的吗?
  • // = xml 中的每一个地方 * = 任何元素 [] = XPath 谓词(一种过滤器)如果你只想在一个项目中使用它,你可以使用 //item/ /*[contains(local-name(),'description')] 表示元素名称包含描述的 item 的后代的任何元素
  • @Sybrentjuhh 你可能想使用&lt;xsl:for-each select="description/*[starts-with(name(),'description')]"&gt;。我说“可能”是因为您没有明确说明该指令的上下文是什么。通常,您的路径越具体,所需的处理就越少。使用子轴的路径比使用后代轴的路径更有效。
  • @SiebeJongebloed 我现在实际上遇到了一个我事先没有预料到的新问题。我已经相应地编辑了我的问题,如果你也能帮助我解决这个问题,那就太好了。 :-)
猜你喜欢
  • 2010-10-09
  • 2014-09-15
  • 2020-08-21
  • 1970-01-01
  • 2019-10-27
  • 2012-03-13
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
相关资源
最近更新 更多