2011-11-27 16 views
0

假設我有以下XML:查找與獨生子女父母的同名

<root> 
<parent> 
    <name>Luiz</name> 
    <son><name>Luiz</name</son> 
    <daugther><name>Cristina</name></daughter> 
</parent> 
<parent> 
    <name>Cristina</name> 
    <daugther><name>Cristina</name></daughter> 
</parent> 
<parent> 
    <name>Carolina</name> 
    <daugther><name>Cristina</name></daughter> 
</parent> 
</root> 

我可以使用哪些XPath來測試父,看它是否只有一個孩子(元素兒子或女兒),這與自己具有相同的名稱。在上面的例子中,只有第二個父母(克里斯蒂娜)會驗證測試。值得一提的是,除了兒子,女兒,父母和名字之外,我可能還有許多其他元素。

+0

第一個'name'是「Luiz」的父母呢?它只有一個和自己同名的孩子?你想排除,因爲有一個「女兒」不同的名字? –

+0

是的,我需要能夠判斷是否只有一個孩子(不管是兒子還是女兒),而且這個孩子是以父母的名字命名的。 –

回答

1

我可以使用什麼XPath來測試父級,以查看它是否只有一個與其自己具有相同名稱的子女 (子元素或女兒)。

使用

  /*/parent 
       [count(*[self::daughter or self::son]) =1 
       and 
       name = *[self::daughter or self::son]/name 
       ] 

這裏選擇被命名爲parent頂部元素的所有孩子,都只有一個子元素(除了name子)及其name孩子的字符串值與其他(非name)孩子的name孩子的字符串值相同。

XSLT - 基於驗證

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

<xsl:template match="/"> 
    <xsl:copy-of select= 
     "/*/parent 
       [count(*[self::daughter or self::son]) =1 
       and 
       name = *[self::daughter or self::son]/name] 
     "/> 
</xsl:template> 
</xsl:stylesheet> 

當這個變換所提供的XML文檔施加(具有校正的許多錯誤,使其充分形成的):

<root> 
<parent> 
    <name>Luiz</name> 
    <son><name>Luiz</name></son> 
    <daughter><name>Cristina</name></daughter> 
</parent> 
<parent> 
    <name>Cristina</name> 
    <daughter><name>Cristina</name></daughter> 
</parent> 
<parent> 
    <name>Carolina</name> 
    <daughter><name>Cristina</name></daughter> 
</parent> 
</root> 

它評估XPath表達式並輸出所有選擇的節點(在這種情況下只有一個):

<parent> 
    <name>Cristina</name> 
    <daughter> 
     <name>Cristina</name> 
    </daughter> 
</parent> 
+0

這不適用於我,正如我上面所說的那樣:_「值得一提的是,除兒子,女兒,父母和姓名之外,我可能還有**許多其他元素。」_ –

+0

好的,那麼你可以完成提供一個更現實的例子。查看更新後的答案。 –

+0

這確實有效,因爲我試圖獲取節點,然後計算結果,然後獲取名稱......我感到死路一條,謝謝。 –