2012-07-06 39 views
2

如何使用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後什麼。 謝謝。

+2

約翰,你可能有興趣在更短的和更準確的解決方案。 – 2012-07-06 12:56:51

回答

1

如果你想測試一個屬性值的一部分,你需要使用屬性ID,當然,不是完全不一樣的,你做。

假設,如肖恩·德金說,那你的重點是候選標題元素,

<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> 

會做的伎倆。

+0

它的工作。非常感謝你。 – john 2012-07-06 12:27:38

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」
+0

對不起,我無法使用模板,我需要使用其他方式,如條件或其他方式,因爲在我原來的xml它來的模板下。我的原始XML太大,我無法發佈。 – john 2012-07-06 09:47:04

+0

查看更新的答案。 – 2012-07-06 09:49:25

+0

對不起,這不起作用我編輯我的輸入檢查。 – john 2012-07-06 10:06:04

2

更短和更精確的解決方案是使用標準的XPath函數starts-with()

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

所以,你的代碼片段變爲:

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

+1:快樂學習新東西... – 2012-07-06 15:24:49

+0

@DonRoby:不客氣。 – 2012-07-06 15:30:11

相關問題