Darkonen
Darkonen

Reputation: 23

How do I move nodes in XML using Nokogiri?

I want to move nodes in nokogiri to a parent.

I have this:

<root>
   <resource>
      <photo_1>
         <photo_url>
           img_src
         </photo_url>   
      </photo_1>
      <adress>
      c/street ...
      </adress>
   </resource>

   <resource>
      <photo_1>
         <photo_url>
           img_src
         </photo_url>   
      </photo_1>
      <adress>
      c/street ...
      </adress>
   </resource>
...

What I want to achieve for each node is:

   <resource>
      <photo_url>
           img_src
      </photo_url>   
      <adress>
      c/street ...
      </adress>
   </resource>

h1  = @doc.at_css "photo_url"
div = @doc.at_css "resource"
h1.parent=div

With this code it only does the first node but not the other I also tried with:

@doc.xpath('//resource').each do |node|
    h1  = node.at_css "photo_url"
    div = @doc.at_css "resource"
    h1.parent=div

end

But doesn't work.

Upvotes: 2

Views: 1365

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

Here's how I'd do it. Using your XML:

xml = <<EOT
<root>
  <resource>
    <photo_1>
      <photo_url>
        img_src
      </photo_url>
    </photo_1>
    <adress>
      c/street ...
    </adress>
  </resource>

  <resource>
    <photo_1>
      <photo_url>
        img_src
      </photo_url>
    </photo_1>
    <adress>
      c/street ...
    </adress>
  </resource>
</root>
EOT

Here's the code:

require 'nokogiri'
doc = Nokogiri::XML(xml)

doc.search('photo_url').each do |n|
  n.parent.replace n
end

puts doc.to_xml

The output looks like:

>> <?xml version="1.0"?>
>> <root>
>>   <resource>
>>     <photo_url>
>>         img_src
>>       </photo_url>
>>     <adress>
>>       c/street ...
>>     </adress>
>>   </resource>
>> 
>>   <resource>
>>     <photo_url>
>>         img_src
>>       </photo_url>
>>     <adress>
>>       c/street ...
>>     </adress>
>>   </resource>
>> </root>

Upvotes: 2

Mark Thomas
Mark Thomas

Reputation: 37507

This will do it:

doc = Nokogiri::XML(xml)
doc.xpath('//photo_url').each do |photo|
  old_parent = photo.xpath('ancestor::*[1]').first
  resource = photo.xpath('ancestor::resource').first
  photo.parent = resource
  old_parent.remove
end

Upvotes: 0

Related Questions