xml - XPath表达式有条件地获取相邻节点

标签 xml xpath

我有一个XML文件,内容如下:

<p>
    <r>
        <t xml:space="preserve">Reading is easier, </t>
    </r>
    <r>
        <fldChar fldCharType="begin"/>
    </r>
    <r>
        <instrText xml:space="preserve"> REF _Ref516568558 \r \p \h </instrText>
    </r>
    <r>
        <fldChar fldCharType="separate"/>
    </r>
    <r>
        <t>This is all the text I want to capture</t>
    </r>
    <r>
        <fldChar fldCharType="end"/>
    </r>
    <r>
        <t xml:space="preserve">, in the new Reading view </t>
    </r>
    <r>
        <fldChar fldCharType="begin"/>
    </r>
    <r>
        <instrText xml:space="preserve"> REF _Not516755367 \r \h </instrText>
    </r>
    <r>
        <fldChar fldCharType="separate"/>
    </r>
    <r>
        <t>But not this...</t>
    </r>
    <r>
        <fldChar fldCharType="end"/>
    </r>
    <r>
        <t xml:space="preserve"> Some other text... </t>
    </r>
</p>


我知道我可以使用XPath表达式//instrText[contains(text(), '_Ref')]来获取<instrText xml:space="preserve"> REF _Ref516568558 \r \p \h </instrText>

现在,我要获取的是t<fldChar fldCharType="begin"/>之间的<fldChar fldCharType="end"/>节点内的文本,如果这两个标签之间存在一个instrText且其文本包含'_Ref'instrText[contains(text(), '_Ref']

基于此,从示例xml中,我希望仅返回:<t>This is all the text I want to capture</t>

可以使用单个XPath 1.0表达式完成此操作吗?

最佳答案

试试这个:p/r[preceding-sibling::r[fldChar/@fldCharType='begin'] and following-sibling::r[fldChar/@fldCharType='end']]/t[contains(., '_Ref')]

关于xml - XPath表达式有条件地获取相邻节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879740/

相关文章:

c++ - 读取 xml 节点列表导致段错误

xml - 如何手动验证 SAMLResponse 签名?

php,xml从具有不同属性的标签输出整个值

java - 如何将 XPath 计算范围缩小到单个节点而不是 Java 中的整个文档?

.net - 是否存在类似于System.IO.Path.Combine()的XPath串联操作?

java - 将 xml 转换为 json 而不转换字符串/整数?

python - 如何为具有特定属性值的xml元素选择数据?

android - 如何将 GoogleMap fragment 包装成 LinearLayout?

XSLT:如何检查多个节点是否适用于所有节点的某个值

python - 如何使用 Scrapy 选择器处理不一致的标记?