【问题标题】:How to extract attributes and data with Nokogiri如何使用 Nokogiri 提取属性和数据
【发布时间】:2013-02-24 07:37:04
【问题描述】:

我有一个无法打开的大文件:

... more here

<my_element attr1='123'>
... a lot of text and elements here
</my_element>

<my_element attr1='33'>
... a lot of text and elements here
</my_element>

... more here

我试过“How do I use Nokogiri::XML::Reader to parse large XML files?”:

#!/usr/bin/ruby
require "rubygems"
require "nokogiri"
require "debugger"
require "awesome_print"

file   = ARGV[0]
reader = Nokogiri::XML::Reader(File.open(file))
reader.each do |node|
  if node.name == "PATDOC"
    debugger
    break
  end
end

node.attributes 返回{}

如何从元素中提取属性和内部文本?

【问题讨论】:

  • 改用 XML 解析器。它会让您的生活更轻松。
  • 我有一个很长的文件,我什至无法打开,我可以使用哪个解析器?我在 OS X 中
  • 定义“大”和“长”。
  • 压缩后约 60 MB。
  • 应该使用流式“SAX”解析器处理大 XML 数据文件。 Nokogiri 支持 SAX,并且已记录在案。另见stackoverflow.com/q/10588194/128421。当这个问题被问到 60MB 有点大时,现在我们可以在大多数盒子上使用 Nokogiri 在内存中的正常 DOM 解析来做到这一点。

标签: ruby xpath nokogiri


【解决方案1】:

通常我们使用 Nokogiri 读取整个文件并将其作为 DOM 进行处理。我将示例 XML 包装在另一个节点中,以使其成为有效的 XML,并使用 CSS 访问器只是因为它们更易于阅读:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<xml>
  <my_element attr1='123'> a lot of text and elements here </my_element>
  <my_element attr1='33'>  a lot of text and elements here </my_element>
</xml>
EOT

doc.search('my_element').map{ |n|
  [ n['attr1'], n.children.text ]
}

看起来像:

[
    [0] [
        [0] "123",
        [1] " a lot of text and elements here "
    ],
    [1] [
        [0] "33",
        [1] "  a lot of text and elements here "
    ]
]

【讨论】:

    【解决方案2】:

    你可以用awk 来做,但推荐的方法是XML 解析器。无论如何:

    awk 'BEGIN {FS="</*my_element[^>]+>"} {print $2, $3}' INPUTFILE
    

    注意:这不是完美的解决方案,因为它实际上取决于您的整个输入文件。它所做的是将您的字段分隔符设置为标签,并从文件中打印第二个和第三个“列”。您可能需要对其进行修改。

    【讨论】:

    • 这个看不懂,好像把my_element元素都提取出来了
    猜你喜欢
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 2023-03-14
    • 2021-08-08
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多