当找到第一个元素时如何停止解析?

发布于 2024-08-09 05:22:24 字数 564 浏览 11 评论 0原文

当找到第一个元素时,我想停止解析,即使之后有更多相同的元素。 我在 ruby​​ 上使用 libxml、SAX。
此代码显示每个 元素。
但我想在找到第一个 时停止解析。
因为这个XML文件会很大。 有谁知道通过 SAX 方法找到第一个元素时如何停止解析。

代码

#! ruby -Ku

require 'rubygems'
require 'libxml'
include LibXML

class PostCallbacks
  include XML::SaxParser::Callbacks

  def on_start_element(element, attributes)
    if /usr/ =~ element
      p element
    end
  end
  
end

parser = XML::SaxParser.file('test.xml')
parser.callbacks = PostCallbacks.new
parser.parse

谢谢。

I would like to stop parse when find 1st element even there is more same element after that.
I use libxml,SAX on ruby.
This code show every <usr> element.
But I want to stop parse when find 1st <usr>.
Because this XML file will be huge.
Does anybody know how stop to parse when find 1st element by SAX method.

code

#! ruby -Ku

require 'rubygems'
require 'libxml'
include LibXML

class PostCallbacks
  include XML::SaxParser::Callbacks

  def on_start_element(element, attributes)
    if /usr/ =~ element
      p element
    end
  end
  
end

parser = XML::SaxParser.file('test.xml')
parser.callbacks = PostCallbacks.new
parser.parse

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花伊自在美 2024-08-16 05:22:24

我不知道这是否也适用于 Ruby,但对于 Python SAX 模块,必须抛出异常才能退出“解析”阶段……这是无需黑客攻击即可完成此操作的唯一方法。

我想如果您没有在 Ruby 文档中找到方法,这可能意味着我的建议是明智的;-)

I don't know if this is also applicable under Ruby but for the Python SAX module, one must throw an exception to get out of the "parse" phase... it is the only way to do it without hacking.

I guess if you didn't find a method in the Ruby documentation, that probably means my proposal is sensible ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文