在 Ruby 中遍历 XML 的子节点时出现问题

Issue with iterating through child nodes of XML in Ruby

我想遍历 Ruby 中 XML 的主节点的子节点,但我得到的输出不是预期的。

这是我的 XML:

<?xml version="1.0"?>
<main>
    <sub>
      <a></a>
      <b></b>
    </sub>
</main>

我需要遍历 "sub" 的子节点:

require 'nokogiri'
f = File.open('test.xml')
doc = Nokogiri::XML(f)

main_node = doc.xpath("//main/sub").first
subnode = main_node.children

subnode.each do |node|
    puts "#{node.name}"
end

我期望输出为:

  a
  b

但我得到的是

text
a
text
b
text

使用 NOBLANKS 解析选项。

http://www.nokogiri.org/tutorials/parsing_an_html_xml_document.html#parse_options

doc = Nokogiri::XML(f) do |config|
  config.noblanks
end

I am not sure how blank nodes are being inserted.

考虑这个简单的例子:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<html><body><p></p></body></html>
EOT

doc.at('p').next_sibling # => nil

doc = Nokogiri::HTML(<<EOT)
<html>
  <body>
    <p></p>
  </body>
</html>
EOT

doc.at('p').next_sibling # => #<Nokogiri::XML::Text:0x3fde488b63b4 "\n  ">
doc.at('p').next_sibling.to_html # => "\n  "

在non-formatted/non-prettified/squashedHTML中,节点之间通常没有空格,除非它在文本中很重要或者在语法上正确HTML;否则浏览器或解析器就没有必要了。

我们添加了空格以使其更易读,但嵌入的换行符和用于缩进的 tabs/spaces 必须以某种方式加以考虑,因此它们被视为文本节点。通常我们不关心,因为我们导航文档以查找特定节点及其嵌入的内容很方便地带我们 around/past 和 "formatting nodes",但它们仍然存在并且它们对文档的结构很重要。