dom4j 中的元素偏移和覆盖文本
我们需要处理一个包含 PCDATA 元素的 XML 文件,如下所示:
<corpus id="c01">
<text id="t01>
<sentence id="s01">Mary <instance id="i01">had</instance> a <instance id="i02">lamb</instance>.</sentence>
<sentence id="s02">...</sentence>
...
</text>
...
</corpus>
对于每个
因此对于上面的例子,我们基本上需要以下内容:
s.id = "s01"
s.text = "Mary had a lamb."
i1.id = "i01"
i1.start = 6
i1.end = 8
i2.id = "i02"
i2.start = 12
i2.end = 15
有没有办法用 dom4j 做到这一点? Element.getText() 方法会跳过子元素的文本,并且我没有看到任何给出元素在另一个元素中的偏移量的方法。如果 dom4j 不适合此任务,那么什么是更好的工具?
We need to process an XML file which contains PCDATA elements like the following:
<corpus id="c01">
<text id="t01>
<sentence id="s01">Mary <instance id="i01">had</instance> a <instance id="i02">lamb</instance>.</sentence>
<sentence id="s02">...</sentence>
...
</text>
...
</corpus>
For each <sentence> of each <text>, we need to populate a data structure containing the sentence ID and the full text covered by the sentence. Then for each <instance>, we need to populate a data structure containing the instance ID and its start and end position within the sentence. (We don't care whether or not the white space is normalized.)
So for the above example, we basically need the following:
s.id = "s01"
s.text = "Mary had a lamb."
i1.id = "i01"
i1.start = 6
i1.end = 8
i2.id = "i02"
i2.start = 12
i2.end = 15
Is there any way of doing this with dom4j? The Element.getText() method skips over the text of child elements, and I don't see any methods which give the offset of an element within another. If dom4j isn't appropriate for this task, what's a better tool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这当然是可行的,但需要做一些工作。您可以创建一个访问者来跟踪它在树中的位置,并随着它的进展累积文本和实例偏移量。然而,该解决方案也可以直接由 SAX 处理程序实现,这样会快得多。
这应该给出一些开始:
It is certainly doable, but requires a little work. You could create a Visitor that keeps track of where it is in the tree and accumulates the text and instance offsets as it progresses. However, that solution could just as well be implemented by a SAX handler directly, which would be a lot faster.
This should give something to start with: