Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Ruby Cookbook | Checking XML Well-Formedness

パンくず

Ruby Cookbook
Checking XML Well-Formedness

概要

Checking XML Well-Formedness

内容

XMLをパースすることでXMLの正当性を検証できる。

サンプルコード

# encoding: utf-8
require 'rexml/document'

VALID_HOGE_XML = %{
<hoge>
  <child_hoge>child_hoge</child_hoge>
</hoge>
}
INVALID_HOGE_XML = %{
<hoge>
  <child_hoge>child_hoge</child_hoge>
}

def valid_xml?(xml)
 begin
   REXML::Document.new(xml)
   true
 rescue REXML::ParseException
   false
 end
end

def print_xml(xml)
  if valid_xml?(xml)
    doc = REXML::Document.new(xml)
    puts doc.root
  else
    puts "invalid xml!"
  end
end

print_xml(VALID_HOGE_XML)
print_xml(INVALID_HOGE_XML)

出力

<hoge>
  <child_hoge>child_hoge</child_hoge>
</hoge>
invalid xml!