如何迭代 Nokogiri XML DocumentFragment 中特定名称的子节点?
给定一个名为“string”的字符串中的 XML:
<Guide>
<Master>
<Part>12345</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>B</Name>
</Sub>
</Master>
<Master>
<Part>XYZABC</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>C</Name>
</Sub>
</Master>
</Guide>
以及这行代码:
bgdoc = Nokogiri::XML::DocumentFragment.parse(xstring.to_xml)
我想循环遍历名为“Part”的所有节点。
我尝试了以下方法:
bgdoc.xpath("//Part").each do |node|
和:
bgdoc.children.each do |node|
next unless node.name=="Part"
但这没有用。
Given this XML in a string called "string":
<Guide>
<Master>
<Part>12345</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>B</Name>
</Sub>
</Master>
<Master>
<Part>XYZABC</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>C</Name>
</Sub>
</Master>
</Guide>
And this line of code:
bgdoc = Nokogiri::XML::DocumentFragment.parse(xstring.to_xml)
I want to loop through all nodes named "Part".
I tried the following:
bgdoc.xpath("//Part").each do |node|
and:
bgdoc.children.each do |node|
next unless node.name=="Part"
But that didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题在于,将 XML 解析为片段会返回部分 XML 文档,即
DocumentFragment
,它没有根:而完整的 XML 文档确实有根:
默认情况下 Nokogiri 是使用像
//Path
这样的 XPath 从文档的根目录进行搜索:但是由于缺少根目录,片段失败:
诀窍是告诉 Nokogiri 在处理片段时要在哪里查找。使用相对搜索或通配符:
或
The problem is that parsing the XML as a fragment returns a partial XML document, i.e., a
DocumentFragment
, which doesn't have a root:whereas a full XML document does have a root:
By default Nokogiri is going to search from the root of the document with an XPath like
//Path
:But that fails with the fragment because of the missing root:
The trick is to tell Nokogiri where to look when dealing with the fragment. Using a relative search or a wildcard:
or
如果您只有一个字符串,只需使用
Nokogiri:XML
进行解析即可:将为您提供一个根,您可以根据需要使用 xpath
//Part
。If you do have just a string, simply parsing with
Nokogiri:XML
instead:will give you a root from which you can use the xpath
//Part
as you expected.应该做这项工作。
should do the job.