2016-10-18 19 views
0

中:XSLT2 - 測試哪個節點至上鑑於這種結構的選項

<body> 
    <h1>Main Title</h1> 
    <p class="sectiontitle>Title</p> 
    <p class="bodytext">some text</bodytext> 
    <ul>...</ul> 
    <p class="paragraphtitle>Subtitle</p> 
    <p class="bodytext">some text</bodytext> 
</body> 

或這一個地方的paragraphtitle和sectiontitle被顛倒:

<h1>Main Title</h1> 
    <p class="paragraphtitle>Title</p> 
    <p class="bodytext">some text</bodytext> 
    <ul>...</ul> 
    <p class="sectiontitle>Subtitle</p> 
    <p class="bodytext">some text</bodytext> 
</body> 

我改造這個XML結構到不同XML(DITA)的味道,爲此,我需要知道節點的第一位,因爲它告訴我如何處理文件的其餘部分。
除非我知道最先發生什麼,否則沒有其他辦法可以處理該文件。
我知道在任何這些標題之前都會有h1,h2,h3 ...元素。主標題和結束標籤之間可能有<p class=bodytext>元素。這是非常隨機的。

我該如何判斷第一個內容:sectiontitle p或paragraphtitle p。

我曾與一些瘋狂的表情放在一個試圖選擇像:

body/p[@class='sectiontitle'][1]/preceding-sibling::p[@class!='paragraphtitle'][last()]/preceding-sibling::*[not(self::p[@class='sectiontitle' or @class='paragraphtitle']) and preceding-sibling::h1] 

body/p[@class='paragraphtitle'][1]/preceding-sibling::p[@class!='sectiontitle'][last()]/preceding-sibling::*[not(self::p[@class='sectiontitle' or @class='paragraphtitle']) and preceding-sibling::h1] 

,在大多數情況下(仍然需要調整的東西)的作品,但我覺得有必須更簡單地告訴哪個節點在可能性列表中首先出現。

有沒有辦法獲得絕對位置?像

if absposition(paragraphtitle[1]) < absposition(sectiontitle[1]) then 
+0

爲什麼你需要知道哪個是第一位的?你試圖在這裏解決的**真正**問題是什麼? –

+0

我想識別文件以知道如何處理它,我知道2個形狀:首先是段落標題,首先是段落標題,基於此,我爲每一個採取不同的路徑。 – Flag

回答

0

有沒有辦法獲得絕對位置?喜歡的東西,如果 absposition(paragraphtitle[1]) < absposition(sectiontitle[1]) then

我相信作爲你的條件可以重申:

如果在第一sectiontitleparagraphtitle,然後...

這可以表示爲:

<xsl:choose> 
    <xsl:when test="/body/p[@class='sectiontitle'][1]/preceding-sibling::p[@class='paragraphtitle']">paragraph title is first</xsl:when> 
    <xsl:otherwise>section title is first</xsl:otherwise> 
</xsl:choose> 

這對XSLT 1.0和2.0都有效。如前所述,在XSLT 2.0,你可以模擬測試,從而精確匹配你原來的語句:

<xsl:when test="/body/p[@class='paragraphtitle'][1] &lt;&lt; /body/p[@class='sectiontitle'][1]">paragraph title is first</xsl:when> 

或:

<xsl:when test="/body/p[@class='sectiontitle'][1] >> /body/p[@class='paragraphtitle'][1]">paragraph title is first</xsl:when> 
+0

這比我預想的要簡單得多,而且還有訣竅。謝謝! – Flag

0

東西在XSLT 2.0中,您可以使用<<操作:

if (p[@class='paragraphtitle'] << p[@class='sectiontitle']) ... 

在1.0你已經有了比前同輩及以下的同胞沒有實際的選擇。但我不能詳細提供詳細信息,因爲您的候選表達式包含了不需要區分這兩個樣本的詳細信息(例如測試兩者中存在的h1元素),並且我假設您將這些額外條件放入這是有原因的。

另一個選項(需要節點集擴展)是通過排除所有不感興趣的元素來過濾列表,然後使用<xsl:if test="p[1][self::sectiontitle]">測試已過濾列表。

或者你也許應該問你爲什麼這樣做,真正的潛在問題是什麼?也許你的真正目標是重新排列元素到一些規範的順序,在這種情況下,我們應該看看排序技術。

+0

謝謝你的回答Michael。我添加了一些信息,但我面對的文件差異很大。我剛剛找到了node-before函數,試圖找到你提到的<<運算符的信息。我要去試試看。 – Flag

+0

請注意,如果不將其作爲「< <」轉義,則不能使用「<<」運算符。 –

+0

@Flag op:node-before函數就是作爲指定'<<'運算符的語義的一種方式。該功能對用戶應用程序不可用。 –