From the xml file provided by the Japan Meteorological Agency with Ruby rexml I am trying to get the alarm information and make some judgment according to the situation.
Ruby 2.6.3 require 'rexml/document'
Parse the following files and put them in doc.
<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="http://xml.kishou.go.jp/jmaxml1/" xmlns:jmx="http://xml.kishou.go.jp/jmaxml1/" xmlns:jmx_add="http://xml.kishou.go.jp/jmaxml1/addition1/">
--- Omitted between ---
<Head xmlns="http://xml.kishou.go.jp/jmaxml1/informationBasis1/">
--- Omitted between ---
<Headline>
<Text>In Osaka Prefecture, be careful of landslides, severe gusts such as tornadoes, and lightning strikes.</Text>
<Information type="Weather warnings / warnings (prefectural forecast areas, etc.)">
<Item>
<Kind>
<Name>Heavy rain warning</Name>
<Code>10</Code>
</Kind>
<Kind>
<Name>Lightning warning</Name>
<Code>14</Code>
</Kind>
<Areas codeType="Meteorological information / prefecture forecast zone, subdivision area, etc.">
<Area>
<Name>Osaka</Name>
<Code>270000</Code>
</Area>
</Areas>
</Item>
</Information>
Less than,<Information>Followed by
I want to turn each statement with the element
item = doc.elements['//Item']
item.each do |kind|
puts kind
end
This caused a problem because the each statement was sent to all the child elements.
--Use REXML :: XPath.match (answered)
require 'rexml/document'
doc = REXML::Document.new(File.read('index.xml'))
kinds = REXML::XPath.match(doc, '/Item/Kind')
kinds.each do |kind|
puts kind.to_s
end
--Use get_elements (self-solving)
doc=REXML::Document.new(open(osaka.xml))
doc.get_elements('//Information/Item/Kind') do |kind|
puts kind
end
The results were the same for both, but what's the difference? Find out if both are the same.
https://docs.ruby-lang.org/ja/latest/method/REXML=3a=3aElement/i/get_elements.html
Recommended Posts