Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active December 15, 2015 02:29
Show Gist options
  • Save tkfm-yamaguchi/5187918 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/5187918 to your computer and use it in GitHub Desktop.
# coding: utf-8
require 'nokogiri'
require 'active_support/core_ext'
module MakeBlankXML
class << self
def execute
org_doc = Nokogiri::XML(DAMMY_XML)
blank_doc = Nokogiri::XML::Builder.new(encoding: "utf-8") do |_|
org_doc.element_children.each do |elem|
emptify_texts(_, elem)
end
end
puts blank_doc.to_xml
end
def emptify_texts(_, elem)
attributes = nil
if elem.attributes.present?
attributes = elem.attributes.inject({}){|h, (k, v)| h[k.intern] = nil; h }
end
_.send(elem.name.intern, attributes) do
# Suppose that if elem.element_children is empty,
# this block do nothing.
elem.element_children.each do |child|
emptify_texts(_, child)
end
end
end
end
DAMMY_XML =<<-EOX
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<person id="002">
<name>Jet Black</name>
<age>35</age>
<properties count="1">
<ship>Bebop</ship>
</properties>
</hoge>
</root>
EOX
end
<?xml version="1.0" encoding="utf-8"?>
<root>
<person id="">
<name/>
<age/>
<properties count="">
<ship/>
</properties>
</person>
</root>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment