RubyでXMLファイルを読み込み、複数の中から特定のエレメントの値を取得する
以下のようなXMLファイルを用意します。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>sample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>Maven Quick Start Archetype</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
このxmlのうち、junitのバージョンを取得してみます。
コメントが結果です。
require 'rexml/document' doc = REXML::Document.new(File.open("pom.xml")) version = doc.elements["/project/dependencies/dependency/version"].text puts version #3.8.1 groupId = doc.root.elements["dependencies"].elements["dependency"].elements["groupId"].text puts groupId #junit
ちょっと解析しているpom.xmlに追記してみます。
dependencyという要素を2つにして、兄弟にします。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>sample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>Maven Quick Start Archetype</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11-beta2</version> </dependency> </dependencies> </project>
dependencyが2つあるうちの、artifactIdが"poi"のものの、versionの値を取得してみます。
中にはエレメントを一つ一つ走査するサンプルも入れました。
require 'rexml/document' doc = REXML::Document.new(File.open("pom.xml")) #これはただのエレメントを走査するサンプル doc.root.elements['//project'].elements.each do | elem | puts "---------" puts elem.name puts elem.text end #poiのバージョンを取得する dependencies = doc.root.elements["/project/dependencies"].elements.each do | dependency | puts "---------" dependency.elements.each do | elem | #puts elem.name if elem.name == "artifactId" if elem.text == "poi" version = elem.next_element puts elem2.text #3.11-beta2←これで取得することができた! end end end end
参考)
http://ruby-doc.org/stdlib-1.9.3/libdoc/rexml/rdoc/REXML/Element.html
http://stackoverflow.com/questions/9992178/getting-the-innerxml-of-an-element-using-rexml-document-and-ruby
http://yakinikunotare.boo.jp/orebase/index.php?Ruby%2FXML%A4%F2%C6%C9%A4%E0#b7d8f557
http://d.hatena.ne.jp/aoi_273/20090311/1236764850
- 作者: 青木峰郎,後藤裕蔵,高橋征義,まつもとゆきひろ
- 出版社/メーカー: ソフトバンククリエイティブ
- 発売日: 2010/08/28
- メディア: 単行本
- 購入: 5人 クリック: 83回
- この商品を含むブログ (32件) を見る