swapping tags & deleting tags via nokogiri

P

pablitoman

let's say I have an xml document like this

<document>
<abcde>
<fghij>
some text blah blah
</fghij>
</abcde>
</document>

is there a simple method in nokogiri to:

step 1: convert all <fghij> tags to something else (e.g., <h1>)
creating this…
<document>
<abcde>
<h1>
some text blah blah
</h1>
</abcde>
</document>

step 2: remove all <abcde> tags but keep the internal tags, creating
this
<document>
<h1>
some text blah blah
</h1>
</document>


I imagine that step 2 is done all the time and there's probably a
simple way to do it, but I'm not sure where to begin with either.

file = Nokogiri::XML(File.new(file_name)) # <= this is about as far
as I've gotten (not very...)

Thanks!!
 
M

Mike Dalessio

let's say I have an xml document like this

<document>
<abcde>
<fghij>
some text blah blah
</fghij>
</abcde>
</document>

is there a simple method in nokogiri to:

step 1: convert all <fghij> tags to something else (e.g., <h1>)
creating this=85
<document>
<abcde>
<h1>
some text blah blah
</h1>
</abcde>
</document>

step 2: remove all <abcde> tags but keep the internal tags, creating
this
<document>
<h1>
some text blah blah
</h1>
</document>


I imagine that step 2 is done all the time and there's probably a
simple way to do it, but I'm not sure where to begin with either.

file =3D Nokogiri::XML(File.new(file_name)) # <=3D this is about as far
as I've gotten (not very...)
Try Loofah, which is based on Nokogiri:

require "loofah"

xml =3D <<-eoxml
<document>
<abcde>
<fghij>
some text blah blah
</fghij>
</abcde>
</document>
eoxml

doc =3D Loofah.xml_document(xml)
scrubber =3D Loofah::Scrubber.new do |node|
node.name =3D "h1" if node.name =3D=3D "abcde"
if node.name =3D=3D "fghij"
node.before node.inner_html
node.remove
end
end
doc.scrub!(scrubber)
puts doc.to_s
# =3D> <?xml version=3D"1.0"?>
# <document>
# <h1>
# some text blah blah
# </h1>
# </document>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top