我正在尝试提取一篇文章的各个部分(简介、历史、概述......)。我寻找一个 XPath 来选择以标题开头并包含一些段落的所有部分。如果它们只包含一个列表,则应将其丢弃。
例如:
<h2>Intro</h2>
<p> It has paragraph and should be extracted </p>
.....
<h2>References </h2>
<ul>...It has just list and should be discarded </ul>
<h2>...</h2>
....
如果 XPath 不可行,XQuery 也可以工作。 我尝试了以下 XQuery
for $x in doc("test.xq")//h2
return
<section>{$x/following-sibling::*[preceding-sibling::h2[1] is $x]}</section>
它根据我的需要选择部分,但我无法对其强加条件(不仅仅是 ul
)。
最佳答案
您在另一个问题中提到这是在 BaseX 中,它支持 XQuery 3.0 group by
机制,那么这样如何:
for $x in doc("test.xq")//h2/following-sibling::*[not(self::h2)]
group by $hId := generate-id($x/preceding-sibling::h2[1])
return
if ($x[not(self::ul)]) then
<section>{($x/preceding-sibling::h2[1], $x)}</section>
else ()
在这里,我首先找到我们想要聚集在一起的所有非 h2 元素(根据 XML 的结构,可能有更有效的方法来做到这一点),然后是 group by
意味着在每次“迭代”中,$x
变量将是一个 h2 与下一个 h2 之间的非 h2 元素序列。然后,if
条件检查该组中是否至少有一个元素不是 ul
。
关于XPath 或 XQuery 排除仅包含列表的文章部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30710968/