Ruby程序中创建和解析XML文件的方法
使用builder创建XML
builder安装方法:
geminstallbuilder
require'builder'
x=Builder::XmlMarkup.new(:target=>
$stdout,:indent=>1)
#":target=>$stdout"参数:指示输出内
容将被写向标准输出控制台
#":indent=>1"参数:XML输出形式将被缩
进一个空格字符x.instruct!:xml,
:version=>'1.1',:encoding=>'gb2312'
x.comment!"书本信息"
x.library("shelf"=>"RecentAcquisitions"){
x.section("name"=>"ruby"){
x.book("isbn"=>"0672310001"){
x.title"ProgrammingRuby"
x.author"Yukihiro"
x.description"ProgrammingRuby-
ThePragmaticProgrammer'sGuide"
}
}
}
px#打印XML
Ruby创建XML输出结果:
<?xmlversion="1.1"encoding="gb2312"?> <!--书本信息--> <libraryshelf="RecentAcquisitions"> <sectionname="ruby"> <bookisbn="0672310001"> <title>ProgrammingRuby</title> <author>Yukihiro</author> <description>ProgrammingRuby-The PragmaticProgrammer'sGuide </description> </book> </section> </library> <inspect/> #<IO:0x2a06ae8>
使用ReXML解析XML
REXML是一个完全用ruby写的processor,他有多种api,其中两个经典的api是通过DOM-like和SAX-like来进行区分的。第一种是将整个文件读进内存,然后存储为一个分层的形式(也就是一棵树了).而第二种是"parseasyougo",当你的文件很大,并且内存受到限制的时候,比较适合用这种。
看下面的book.xml:
引用
<libraryshelf="RecentAcquisitions"> <sectionname="Ruby"> <bookisbn="0672328844"> <title>TheRubyWay</title> <author>HalFulton</author> <description> Secondedition.Thebookyouarenowreading. Ain'trecursiongrand? </description> </book> </section> <sectionname="Space"> <bookisbn="0684835509"> <title>TheCaseforMars</title> <author>RobertZubrin</author> <description>Pushingtowardasecondhomeforthehuman race. </description> </book> <bookisbn="074325631X"> <title>FirstMan:TheLifeofNeilA.Armstrong</title> <author>JamesR.Hansen</author> <description>Definitivebiographyofthefirstmanon themoon. </description> </book> </section> </library>
1TreeParsing(也就是DOM-like)
我们需要requirerexml/document库,并且includeREXML:
require'rexml/document'
includeREXML
input=File.new("books.xml")
doc=Document.new(input)
root=doc.root
putsroot.attributes["shelf"]#RecentAcquisitions
doc.elements.each("library/section"){|e|putse.attributes["name"]}
#Output:
#Ruby
#Space
doc.elements.each("*/section/book"){|e|putse.attributes["isbn"]}
#Output:
#0672328844
#0321445619
#0684835509
#074325631X
sec2=root.elements[2]
author=sec2.elements[1].elements["author"].text#RobertZubrin
这里要注意的是xml中的属性和值被表示为一个hash,因此我们能够通过attributes[]来提取我们需要的值,元素的值还能通过类似于path的字符串或者整数来取得.其中用整数取的话,是1-based而不是0-based.
2 StreamParsing(也就是SAX-likeParsing)
这边使用了一个小技巧,那就是定义了一个listener类,它将会在parse的时候被回调:
require'rexml/document'
require'rexml/streamlistener'
includeREXML
classMyListener
includeREXML::StreamListener
deftag_start(*args)
puts"tag_start:#{args.map{|x|x.inspect}.join(',')}"
end
deftext(data)
returnifdata=~/^\w*$/#whitespaceonly
abbrev=data[0..40]+(data.length>40?"...":"")
puts"text:#{abbrev.inspect}"
end
end
list=MyListener.new
source=File.new"books.xml"
Document.parse_stream(source,list)
这里介绍一下StreamListener模块,这个模块它提供了几个空的回调方法,因此你可以为了实现你自己的功能而覆盖它.当parser进入一个tag时,就会调用tag_start方法.而text方法也是类似的,他只不过是当读取到数据时会被回调,它的输出是这样的:
tag_start:"library",{"shelf"=>"RecentAcquisitions"}
tag_start:"section",{"name"=>"Ruby"}
tag_start:"book",{"isbn"=>"0672328844"}
tag_start:"title",{}
text:"TheRubyWay"
.........................................
3XPath
REXML通过XPath类来提供Xpath的支持.它也同时支持DOM-like和SAX-like.还是前面的那个xml文件,我们使用Xpath可以这样做:
book1=XPath.first(doc,"//book")#Infoforfirstbookfound
pbook1
#Printoutalltitles
XPath.each(doc,"//title"){|e|putse.text}
#Getanarrayofallofthe"author"elementsinthedocument.
names=XPath.match(doc,"//author").map{|x|x.text}
pnames
输出是类似于下面的:
<bookisbn='0672328844'>...</> TheRubyWay TheCaseforMars FirstMan:TheLifeofNeilA.Armstrong ["HalFulton","RobertZubrin","JamesR.Hansen"]