2011-02-23 85 views
7

我想知道XPath是否可以返回一個數組值。如何使用XPath返回數組?

我成才這樣的:

<Cities> 
    <City>Paris</City> 
    <City>Lyon</City> 
    <City>Marseille</City> 
</Cities> 

而且我想獲得這種形式[「巴黎」,「里昂」,「馬賽」]數組。

我正在使用xpath UNIX實用程序。

有什麼想法?

+0

這不是確切的,但它是相同的[如何從Dom4j Node.selectObject或Node.selectNodes獲取字符串列表](http://stackoverflow.com/questions/4628647/how-to-get-a-list -of-字符串從-DOM4J-節點選擇對象或 - 節點的selectNodes)。如果你想要一個序列數據類型的結果,你必須使用XPath 2.0 – 2011-02-23 15:17:49

+0

好問題,+1。請參閱我的回答以獲得解釋和解:) – 2011-02-23 17:45:24

回答

5

除了後處理的輸出:

xpath -q -e '//City/text()' inputfile 

它是:

Paris 
Lyon 
Marseille 
在任何數量的方式

,包括:

xpath -q -e '//City/text()' inputfile | 
    awk 'BEGIN {sq = "\047"; OFS = sq "," sq} 
     {a[$1] = NR} 
     END { 
      printf "[" sq; 
      for (i in a) { 
       printf "%s%s", d, i; d = OFS}; 
      print sq "]" 
     }' 

這給出了輸出:

['Lyon','Marseille','Paris'] 

您可以使用我的修改版本xpath。由於它是一個簡單的Perl腳本,因此我對它進行了修改,以便更好地控制輸出的格式。用我的版本,你可以這樣做:

xpath -q -b "[" -p "'" -i "," -s "'" -a "]"$'\n' -e '//City/text()' 

得到想要的輸出。以下是使用信息:

Usage: 
xpath [options] -e query [-e query...] [filename...] 

     If no filenames are given, supply XML on STDIN. 
     You must provide at least one query. Each supplementary 
     query is done in order, the previous query giving the 
     context of the next one. 

     Options: 

     -q quiet  Only output the resulting PATH 
     -b before  use before instead of nothing. 
     -p prefix  use prefix instead of nothing. 
     -s suffix  use suffix instead of linefeed. 
     -i infix  use infix instead of nothing. 
     -a after  use after instead of nothing. 

您可以download my version here

1

我知道在.Net你可以在xmlDocumentxDoc.SelectNodes("//City");它提供了一個節點列表,並且您可以使用NODE.FirstChild.Value來獲取名稱。

1

這個XPath表達式

/*/*/text() 

選擇正好三個想文本節點。

可以以與陣列狀符號使用它:

/*/*/text()[1] 

選擇文本節點

"Paris" 

/*/*/text()[2] 

選擇文本節點

"Lyon" 

/*/*/text()[3] 

選擇文本節點

"Marseille" 

如果你想只是這些文本節點的字符串值,使用(例如):

string(/*/*/text()[2]) 

評估此XPath表達式的結果是st環

"Lyon"