これは私のsample.xmlです:
<?xml version="1.0" encoding="utf-8"?>
<ShipmentRequest>
<Message>
<Header>
<MemberId>MID-0000001</MemberId>
<MemberName>Bruce</MemberName>
<DeliveryId>0000001</DeliveryId>
<OrderNumber>ON-000000001</OrderNumber>
<ShipToName>Alan</ShipToName>
<ShipToZip>123-4567</ShipToZip>
<ShipToStreet>West</ShipToStreet>
<ShipToCity>Seatle</ShipToCity>
<Payments>
<PayType>Credit Card</PayType>
<Amount>20</Amount>
</Payments>
<Payments>
<PayType>Points</PayType>
<Amount>22</Amount>
</Payments>
<PayType />
</Header>
<Line>
<LineNumber>3.1</LineNumber>
<ItemId>A-0000001</ItemId>
<Description>Apple</Description>
<Quantity>2</Quantity>
<UnitCost>5</UnitCost>
</Line>
<Line>
<LineNumber>4.1</LineNumber>
<ItemId>P-0000001</ItemId>
<Description>Peach</Description>
<Quantity>4</Quantity>
<UnitCost>6</UnitCost>
</Line>
<Line>
<LineNumber>5.1</LineNumber>
<ItemId>O-0000001</ItemId>
<Description>Orange</Description>
<Quantity>2</Quantity>
<UnitCost>4</UnitCost>
</Line>
</Message>
</ShipmentRequest>
そして私のsample.rb:
#!/usr/bin/ruby -w
require 'nokogiri'
doc = Nokogiri::XML(open("sample.xml"))
doc.xpath("//ShipmentRequest").each {
|node| puts node.text
}
そして、私が得る結果:
MID-0000001
Bruce
0000001
ON-000000001
Alan
123-4567
West
Seatle
Credit Card
20
Points
22
3.1
A-0000001
Apple
2
5
4.1
P-0000001
Peach
4
6
5.1
O-0000001
Orange
2
4
また、タグ名を出力し、値が空白のタグ/ノードをスキップしたいと思います:
MemberID: MID-0000001
MemberName: Bruce
DeliveryId: 0000001
OrderNumber: ON-000000001
ShipToName: Alan
ShipToZip: 123-4567
ShipToStreet: West
etc...