使用属性检查节点名称

时间:2012-07-06 09:30:55

标签: xml xslt xpath

如何使用xslt?

查找是否存在具有属性值的节点

假设我的xml是这样的

<root>
 <sub>
    <p>text</p>
   <title id='id1-num-444'>text</title>
    <p>text</p>  
   <title id='id1-str-aaa'>text</title>
    <p>text</p>  
   <title id='id1-num-333'>text</title> 
    <p>text</p>  
 </sub>
</root>

我使用了以下xsl

<xsl:template match ="sub">

  ....some tags...

  <xsl:if test ="contains(name(), 'title[@id='id1-num']')">
  <xsl:call-template name ="title"></xsl:call-template>
</xsl:if>
</xsl:template>

if条件需要检查到num,它不应该考虑num之后的任何内容。 感谢。

3 个答案:

答案 0 :(得分:2)

更短更精确的解决方案是使用标准XPath函数starts-with()

starts-with(@id, 'id1-num')

因此,您的代码片段变为:

<xsl:if test="starts-with(@id, 'id1-num')">
   <xsl:call-template name ="title"/>
</xsl:if>

答案 1 :(得分:1)

如果你想测试属性值的一部分,你需要使用contains(),但当然,不像你那样。

正如Sean Durkin所说,假设您的重点是候选标题元素,

<xsl:if test ="contains(self::title/@id,'id1-num')">
    <xsl:call-template name ="title"></xsl:call-template>
</xsl:if>

或稍微不那么明确的

<xsl:if test ="contains(@id,'id1-num')">
    <xsl:call-template name ="title"></xsl:call-template>
</xsl:if>

会做到这一点。

答案 2 :(得分:0)

我们需要更多的上下文来理解你想要的东西,但也许你想要匹配模板规则是这样的? ...

<xsl:template match="title[@id='id1-num']">
  ... contents go here ...
</xsl:template>

如果需要在序列构造函数中进行测试,并且焦点项是候选标题元素,那么也许呢? ...

<xsl:if test ="self::title[@id='id1-num']">
  <xsl:call-template name ="title"></xsl:call-template>
</xsl:if>

在上文中,当且仅当:

时,测试才会通过
  1. 焦点项目是名为title的元素;
  2. 并且它具有值为'id1-num'
  3. 的属性id
相关问题