使用XPath分割节点值

问题描述 投票:10回答:2

XPath中是否存在某种split()函数?说我有这个XML:

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

而且我想检索filename,我该怎么做?我知道我可以这样获得节点值:

//path/text()

如何仅获取文件名? (我知道有一个concat()函数,所以也许有一个split()函数?)

xml xpath-2.0
2个回答
8
投票

如果您具有支持xpath-2.0的API,则可以通过两种方式解决此问题:

替换技术

尝试使用:

fn:replace(string,pattern,replace)

例如

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

令牌技术

您可能会从标记化中获得一些收益:

fn:tokenize(string,pattern)

例如(感谢马丁)

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

w3schools xml processing "xsl functions" documentation


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
           )
© www.soinside.com 2019 - 2024. All rights reserved.