如何使用 XPath 从一个字符串中的多个元素返回文本? [英] How to return text from several elements in one string using XPath?

查看:13
本文介绍了如何使用 XPath 从一个字符串中的多个元素返回文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 XPath 从所有

  • 元素中提取所有文本,这些元素位于 specialList 列表中,并返回一个由空格分隔的字符串或逗号.这可能吗?

    I would like to use XPath to extract all the text from all the <li> elements, that are in the specialList list and return one string separated by spaces or commas. Is this possible?

    假设 DOM 包含以下 HTML:

    Lets say the DOM includes the following HTML:

    <ul class="specialList">
       <li>one</li>
       <li>two</li>
       <li>three</li>
       <li>four</li>
    </ul>
    

    期望输出

    one, two, three, four
    

    one two three four
    

    推荐答案

    XPath 1.0 中,只有使用 concat(...):

    In XPath 1.0, this is only possible if you know the number of elements in advance using concat(...):

    concat(//li[1], ', ', //li[2], ', ', //li[3], ', ', //li[4])
    

    如果幸运的话,您可以只返回 //li/text() 的所有结果字符串,并设置 XPath 处理器的输出参数以按照您的需要连接它们.这取决于处理器,因此没有通用的解决方案,如果您想在 XPath 中进一步处理结果,这是没有办法的.

    If you're lucky, you can just return all result strings for //li/text() and set the output parameters of your XPath processor to concatenate them like you want. This depends on the processor, so there is no general solution and this is no way to go if you want to further process the results within XPath.

    XPath 2.0中,可以使用fn:string-join($sequence, $deemiter)进行任意长度的输入:

    In XPath 2.0, you can use fn:string-join($sequence, $delemiter) for input of arbitrary length:

    fn:string-join(//li, ', ')
    

    这篇关于如何使用 XPath 从一个字符串中的多个元素返回文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆