[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 ----
      <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.)">
            <Name>Heavy rain warning</Name>
            <Name>Thunder warning</Name>
          <Areas code Type="Weather information/prefecture forecast ward, subdivision area, etc.">
              <Name>Osaka Prefecture</Name>
Below, <Information> continues

I want to turn each statement with the element .

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

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)

doc = REXML::Document.new(File.read('index.xml'))

kinds = REXML::XPath.match(doc,'/Item/Kind')

kinds.each do |kind|
  puts kind.to_s
  • Use get_elements (self-solving)

doc.get_elements('//Information/Item/Kind') do |kind|
  puts kind

Next task

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