Ruby / rexml: Turn each with an element with the same name

What i wanted to do

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'

What didn't work

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 , so first

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.

I found two solutions by asking questions on other sites.

--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

Next challenge

The results were the same for both, but what's the difference? Find out if both are the same.

reference

https://docs.ruby-lang.org/ja/latest/method/REXML=3a=3aElement/i/get_elements.html

Recommended Posts

Ruby / rexml: Turn each with an element with the same name
Ruby, Nokogiri: Get the element name of the selected node
Overwrite upload of file with the same name with BOX SDK (java)
Programming with ruby (on the way)
Send an email from gmail with Ruby
Ruby's fine syntax: if you have variables and methods with the same name
[Ruby] Define the hierarchy at the same time as Hash initialization with tap method