我在XML文件开头的注释中有XML和其他数据。 我想阅读一些日志记录的这些细节。
有没有办法在Ruby中读取XML注释值?
评论的详细信息如下:
<!-- sessionId="QQQQQQQQ" --><!-- ProgramId ="EP445522" -->
答案 0 :(得分:3)
使用Nokogiri和XPath提取值:
require 'rubygems'
require 'nokogiri'
doc = Nokogiri::XML('<!-- sessionId="QQQQQQQQ" --><!-- ProgramId ="EP445522" -->')
comments = doc.xpath('//comment()')
tags = Hash[*comments.map { |c| c.content.match(/(\S+)\s*="(\w+)"/).captures }.flatten]
puts tags.inspect
# => {"sessionId"=>"QQQQQQQQ", "ProgramId"=>"EP445522"}
答案 1 :(得分:2)
你可以这样做:
require 'rexml/document'
require 'rexml/xpath'
File::open('q.xml') do |fd|
xml = REXML::Document::new(fd)
REXML::XPath::each(xml.root, '//comment()') do |comment|
case comment.string
when /sessionId/
puts comment.string
when /ProgramId/
puts comment.string
end
end
end
有效的做法是遍历所有评论节点,然后查找您感兴趣的字符串,例如sessionId
。一旦找到了您正在寻找的节点,您就可以使用Ruby处理它们以提取您需要的信息。