2013-05-15 38 views
1
<chapter> 
    <concept> 
     <title>*********************</title> 
    . 
    . 
    </concept> 

    <sections> 
     <title>*******************</title> 

</chapter> 

在上述結構中,我想從<concept><title><sections><title>中檢索文本。即使用一個xpath條件,我需要以下條件的值。XPATH以條件值顯示

1)如果<concept><title>未出現,則出現<sections><title>。副反轉也..

2)兩個標題都可用,那麼我想考慮nearst節點值。即在上述結構中「<sections><title>」是最新的節點。

回答

0

換句話說,你只是想要最後concept/titlesections/title發生在chapter?這個XPath應該這樣做(假設當前上下文chapter

(concept/title | sections/title)[last()] 
1

你想要的 「最近」(兩在前):

(/*/*[self::concept or self::sections]/title)[1] 

如果你想 「最新」 (最後)其中,使用方法:

(/*/*[self::concept or self::sections]/title)[last()] 

XSLT - 基於驗證

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

<xsl:template match="/"> 
    <xsl:copy-of select= 
    "(/*/*[self::concept or self::sections]/title)[1]"/> 
=============== 
    <xsl:copy-of select= 
    "(/*/*[self::concept or self::sections]/title)[last()]"/> 
</xsl:template> 
</xsl:stylesheet> 

當在下面的XML文檔被應用於這種轉變:

<chapter> 
    <concept> 
     <title>*********Title 1************</title> 
    . 
    . 
    </concept> 

    <sections> 
     <title>**********Title 2*********</title> 
    </sections> 

</chapter> 

兩個的XPath表達式,並且它們的結果複製到輸出:

<title>*********Title 1************</title> 
=============== 
<title>**********Title 2*********</title> 
+0

對我來說看起來不錯。 –

+0

@ hr_117,不客氣。是的,除非已知使用XPath處理器正在優化此類表達式,否則這比從聯合中指定第一個節點更有效。 –