[Ruby] Ruby/rexml: Rotate each with same name element

1 minute read

What you wanted to do

From xml file provided by JMA with Ruby rexml I’m trying to get the warning 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/">
  --- Omitting ----
  <Head xmlns="http://xml.kishou.go.jp/jmaxml1/informationBasis1/">
    --- Omitting ----
    <Headline>
      <Text>In Osaka Prefecture, be careful of landslides, severe wind gusts such as tornadoes, and lightning strikes. </Text>
      <Information type="Weather warning/warning (prefecture forecast area, etc.)">
        <Item>
          <Kind>
            <Name>Heavy rain warning</Name>
            <Code>10</Code>
          </Kind>
          <Kind>
            <Name>Thunder warning</Name>
            <Code>14</Code>
          </Kind>
          <Areas code Type="Weather information/prefecture forecast ward, subdivision area, etc.">
            <Area>
              <Name>Osaka Prefecture</Name>
              <Code>270000</Code>
            </Area>
          </Areas>
        </Item>
      </Information>
Below, <Information> continues

I want to turn each statement with the element .

item = doc.elements['//Item']
item.each do |kind|
puts kind
end

In this case, the each sentence was wrapped around all the child elements, which was a problem.

I found two solutions by asking questions on other sites.

  • Use REXML::XPath.match (what you 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 task

Both have the same result, but is there something different? Find out if they are the same.

Reference

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