开发者

How do I move nodes in XML using Nokogiri?

开发者 https://www.devze.com 2023-03-11 15:44 出处:网络
I want to move nodes in nokogiri to a parent. I have this: <root> <resource> <photo_1> <photo_url>

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 "pho开发者_StackOverflow中文版to_url"
    div = @doc.at_css "resource"
    h1.parent=div

end

But doesn't work.


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>


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
0

精彩评论

暂无评论...
验证码 换一张
取 消