【发布时间】:2014-02-02 14:16:06
【问题描述】:
在解析缩进的 XML 时,非重要的空白文本节点是从结束标记和开始标记之间的空白处创建的。例如,来自以下 XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
其字符串表示如下,
"<note>\n <to>Tove</to>\n <from>Jani</from>\n <heading>Reminder</heading>\n <body>Don't forget me this weekend!</body>\n</note>\n"
创建了以下Document:
#(Document:0x3fc07e4540d8 {
name = "document",
children = [
#(Element:0x3fc07ec8629c {
name = "note",
children = [
#(Text "\n "),
#(Element:0x3fc07ec8089c {
name = "to",
children = [ #(Text "Tove")]
}),
#(Text "\n "),
#(Element:0x3fc07e8d8064 {
name = "from",
children = [ #(Text "Jani")]
}),
#(Text "\n "),
#(Element:0x3fc07e8d588c {
name = "heading",
children = [ #(Text "Reminder")]
}),
#(Text "\n "),
#(Element:0x3fc07e8cf590 {
name = "body",
children = [ #(Text "Don't forget me this weekend!")]
}),
#(Text "\n")]
})]
})
这里有很多Nokogiri::XML::Text类型的空白节点。
我想计算 Nokogiri XML Document 中每个节点的 children,并访问第一个或最后一个子节点,不包括非重要的空格。我不希望解析它们,或区分这些和重要的文本节点,例如元素<to> 中的那些,比如"Tove"。这是我正在寻找的 rspec:
require 'nokogiri'
require_relative 'spec_helper'
xml_text = <<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML
xml = Nokogiri::XML(xml_text)
def significant_nodes(node)
return 0
end
describe "Stackoverflow Question" do
it "should return the number of significant nodes in nokogiri." do
expect(significant_nodes(xml.css('note'))).to eq 4
end
end
我想知道如何创建significant_nodes 函数。
如果我将 XML 更改为:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer></footer>
</note>
然后当我创建Document 时,我仍然希望显示页脚;不能使用config.noblanks。
【问题讨论】:
-
Tove 被放置在标签
to内,所以你在shell 中找到标签,然后得到文本:doc.css( 'to' ).text -
amolnpujari.wordpress.com/2012/03/31/reading_huge_xml-rb 我还发现 ox 在读取大型 xml 时比 nokogiri 快 5 倍。另外,我编写了一个包装器,它只允许您使用 ox 搜索大型 xml,允许您使用指定的元素进行迭代。 gist.github.com/amolpujari/5966431
标签: xml-parsing html-parsing nokogiri