我的文字文件如:
<first>1</first><Name>wangli</Name><birthday>19860105</birthday><address>Here</address>
<first>2</first><Name>zhangli</Name><birthday>19870105</birthday><address>Sangdu</address>
<first>3</first><Name>lili</Name><birthday>19880105</birthday><address>Hongkong</address>
<first>4</first><Name>liuli</Name><birthday>19860515</birthday><address>London</address>
我想用ruby gem nokogiri创建一个新文件,如:
wangli-Here
zhangli-Sangdu
lili-Hongkong
liuli-London
我用过:
require 'nokogiri'
doc = Nokogiri::XML(File.open("file"),nil,"gbk")
puts doc.xpath("/name") + doc.xpath("/address")
无法正常工作
答案 0 :(得分:0)
看起来问题已经解决了! 我更改了文本文件:
<doc>
<line><first>1</first><Name>wangli</Name><birthday>19860105</birthday><address>Here</address></line>
<line><first>2</first><Name>zhangli</Name><birthday>19870105</birthday><address>Sangdu</address></line>
<line><first>3</first><Name>lili</Name><birthday>19880105</birthday><address>Hongkong</address></line>
<line><first>4</first><Name>liuli</Name><birthday>19860515</birthday><address>London</address></line>
</doc>
然后是红宝石代码
require 'nokogiri'
doc = Nokogiri::XML(File.open("27065"),nil,"gbk")
doc.xpath("//line").each do |line|
l.xpath("./name").text + "-" + line.xpath("./address").text
end
答案 1 :(得分:0)
由于输入XML的每一行都包含一个XML片段,因此您必须逐个处理每一行。此外,您需要使用Nokogiri::XML.fragment
来解析每一行。这是一个有效的例子:
require "nokogiri"
output = File.open("output.txt", "w")
File.open("input.xml", "r") do |f|
f.each_line do |line|
frag = Nokogiri::XML.fragment(line)
output.puts "#{frag.search('Name').text}=#{frag.search('address').text}"
end
end
output.close