2016-09-12 46 views
0

我需要能夠跟蹤文檔中任何特定值的位置。我會使用XSL,但是我正在使用的生態系統可以防止這種情況發生。我正在使用Java Saxon-HE 9.7.0-2處理器。屬性不匹配時返回空字符串屬性匹配時返回文本

XML

<test> 
    <value cat="fiction">At the edge of the orchard</value> 
    <value cat="mythology">Hero with a thousand faces</value> 
    <value cat="fiction">Spill simmer falter wither</value> 
</test> 

的XPath

for $a in /test 
    return 
     (if ($a/value[@cat="mythology"]) then 
      $a/value[@cat="mythology"] else 
      "") 

我想看到什麼回來的是:

"" 
"Hero with a thousand faces" 
"" 

什麼我目前看到的是:

"Hero with a thousand faces" 

Link to videlibri xpath tester

Link to saxon code

回答

1

我想你想遍歷每個value,做檢查。下面的XPath應該爲你工作:

string-join((for $a in /test/value 
           return 
            (if ($a[@cat='mythology']) then 
             concat('&quot;',$a,'&quot;') else 
             '&quot;&quot;')),'&#xa;') 

簡體:

string-join((for $a in /test/value 
      return 
       concat('&quot;',($a[@cat='mythology'],'')[1], '&quot;')) 
    ,'&#xa;') 
+0

謝謝;它更接近我所需要的,但現在我處於解析回報的位置。我得到這個XPath是:" " "英雄千面" " "解析是有風險的,我因爲在現實中是什麼在那個文本塊是不受約束的。如果我不能想出更好的東西,我仍然可能不得不採用這種解決方案。 – BDF

0

這是返回空字符串我在尋找:

for $a in /test/value 
return 
    if ($a[@cat='mythology']) then 
     $a[@cat='mythology'] else 
     "" 

有人能解釋爲什麼這種行爲的XPath與原始問題中的不一樣?

videlibri xpath tester

+0

爲了回答我自己的問題:'for $ in/test'的原始循環只有一個節點,因此只包含if語句會被評估一次。在有效的版本中;我正在迭代多個節點。當我評估/測試/評估[@ cat ='fiction']本身時沒有循環和if語句,這對我來說已經很清楚了。另一個感謝你讓我走上正確的道路。 – BDF

0

我覺得/test/value/(.[@cat = 'mythology'], '')[1]就足夠了,並且是位比for .. return if ... then ... else更緊湊。