【发布时间】:2012-05-25 20:32:42
【问题描述】:
我的 XML 文档有任意嵌套的部分。鉴于对特定部分的引用,我需要在该部分中找到所有 TextNodes,不包括小节。
例如,给定下面#a1节点的引用,我只需要找到“A1”和“A1”文本节点:
<root>
<section id="a1">
<b>A1 <c>A1</c></b>
<b>A1 <c>A1</c></b>
<section id="a1.1">
<b>A1.1 <c>A1.1</c></b>
</section>
<section id="a1.2">
<b>A1.2 <c>A1.2</c></b>
<section id="a1.2.1">
<b>A1.2.1</b>
</section>
<b>A1.2 <c>A1.2</c></b>
</section>
</section>
<section id="a2">
<b>A2 <c>A2</c></b>
</section>
</root>
如不明显,以上为虚构数据。 id 属性在实际文档中可能不存在。
我现在想出的最好办法是找到该部分中的所有文本节点,然后使用 Ruby 减去我不想要的那些:
def own_text(node)
node.xpath('.//text()') - node.xpath('.//section//text()')
end
doc = Nokogiri.XML(mydoc,&:noblanks)
p own_text(doc.at("#a1")).length #=> 4
我可以制作一个 XPath 1.0 表达式来直接查找这些节点吗?比如:
.//text()[ancestor::section = self] # self being the original context node
【问题讨论】: