2010-11-23 73 views
7

XPath中是否有某種split()函數? 說我有這樣的XML:使用XPath分割節點值

<root> 
    <path>C:\folder\filename</path> 
</root> 

我想要檢索filename,我該怎麼辦呢?我知道我可以得到像這樣的節點值:

//path/text() 

我怎樣才能得到文件名? (?我知道有一個concat()功能,所以也許有一個split()功能)

+0

好問題,+1。除了你已經得到了很好的答案之外,請參閱我的答案以獲取其他兩種可能的解 – 2010-11-23 17:00:02

回答

6

如果你有一個XPath的2.0能力API,你可以通過兩種方式解決這個問題:

替代技術

嘗試使用:

fn:replace(string,pattern,replace) 

fn:replace(//path/text(),".*/","") 

記號化技術

你可以從令牌化得到一些里程:

fn:tokenize(string,pattern) 

例如(感謝馬丁)

tokenize(/root/path, '\\')[last()] 

http://www.w3schools.com/Xpath/xpath_functions.asp#string

+3

是的``tokenize(/ root/path,'\\')[last()]`允許但請注意,replace和tokenize都是XPath 2.0,XPath 1.0中不可用,所以您需要像Saxon 9這樣的XPath 2.0實現(http://saxon.sourceforge.net/)。 – 2010-11-23 11:37:05

1

雖然我會用

tokenize(/*/*, '\\')[last()] 

還有許多其他的方式獲得所需的字符串

codepoints-to-string 
    (reverse 
     (string-to-codepoints 
     (substring-before 
      (codepoints-to-string 
       (reverse 
        (string-to-codepoints(/*/*) 
       ) 
      ), 
       '\' 
      ) 
     ) 
     ) 
    ) 

substring(/*/*, 
      index-of(string-to-codepoints(/*/*), 
      string-to-codepoints('\') 
      ) 
      [last()] 
      + 1 
      )