我有以下XML结构
<?xml version="1.0" encoding="UTF-8"?>
<body>
<division>
<Atopic><longtitle>TitleDiv1 Atopic</longtitle></Atopic>
<Btopic><longtitle>TitleDiv1 Btopic</longtitle></Btopic>
<Ctopic><longtitle>TitleDiv1 Ctopic</longtitle></Ctopic>
<division>
<Atopic><longtitle>TitleDiv1.1 Atopic</longtitle></Atopic>
</division>
<Dtopic><longtitle>TitleDiv2 Dtopic</longtitle></Dtopic>
<Etopic><longtitle>TitleDiv2 Etopic</longtitle></Etopic>
</division>
</body>
我使用`count(ancestor :: division [last()] / * [contains(name(),'topic')])来获取body / division元素下的所有*主题。
我的需要是,如果我使用body/division/division/Atopic
中的上下文,我想只获得正文/部门之前的主题。所以在这种情况下只有
<Atopic><longtitle>TitleDiv1 Atopic</longtitle></Atopic>
<Btopic><longtitle>TitleDiv1 Btopic</longtitle></Btopic>
<Ctopic><longtitle>TitleDiv1 Ctopic</longtitle></Ctopic>
而不是
<Dtopic><longtitle>TitleDiv2 Dtopic</longtitle></Dtopic>
<Etopic><longtitle>TitleDiv2 Etopic</longtitle></Etopic>
因为它位于上下文节点之后。
请建议。
答案 0 :(得分:0)
您的上下文节点://body/division/division/Atopic
您的纯XPath表达式:
//body/division/division/Atopic
/ancestor::division[last()]
/*[contains(name(), 'topic')]
[
count(.| //body/division/division/Atopic/ancestor::division[1]/preceding-sibling::*[contains(name(), 'topic')])
=
count(//body/division/division/Atopic/ancestor::division[1]/preceding-sibling::*[contains(name(), 'topic')])
]
此处有详细解释:xpath-select-all-elements-between-two-specific-elements