当找到第一个元素时如何停止解析?
当找到第一个元素时,我想停止解析,即使之后有更多相同的元素。 我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道这是否也适用于 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 ;-)