Created
January 12, 2010 13:51
-
-
Save flavorjones/275209 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/ruby | |
# in response to ruby-talk email of 2010-01-12 from Anandh Kumar | |
xml = <<EOX | |
<root> | |
<row> | |
<column>Business Strategy</column> | |
<column>bus1</column> | |
</row> | |
<row> | |
<column>Company Description</column> | |
<column>tar1</column> | |
</row> | |
<row> | |
<column>Business Strategy</column> | |
<column>bus2</column> | |
</row> | |
<row> | |
<column>Company Description</column> | |
<column>tar2</column> | |
</row> | |
<row> | |
<column>Business Strategy</column> | |
<column>bus3</column> | |
</row> | |
<row> | |
<column>Company Description</column> | |
<column>tar3</column> | |
</row> | |
</root> | |
EOX | |
require 'rubygems' | |
require 'nokogiri' | |
doc = Nokogiri::XML xml | |
business_nodes = doc.xpath("/root/row/column[text()='Business Strategy']/following-sibling::*") | |
company_nodes = doc.xpath("/root/row/column[text()='Company Description']/following-sibling::*") | |
new_doc = Nokogiri::XML::Builder.new do | |
root do | |
row do | |
column "Business Strategy" | |
business_nodes.each { |node| column node.content } | |
end | |
row do | |
column "Company Description" | |
company_nodes.each { |node| column node.content } | |
end | |
end | |
end | |
puts new_doc.to_xml | |
# <?xml version="1.0"?> | |
# <root> | |
# <row> | |
# <column>Business Strategy</column> | |
# <column>bus1</column> | |
# <column>bus2</column> | |
# <column>bus3</column> | |
# </row> | |
# <row> | |
# <column>Company Description</column> | |
# <column>tar1</column> | |
# <column>tar2</column> | |
# <column>tar3</column> | |
# </row> | |
# </root> |
If you've got questions about how to use Nokogiri, please communicate via the mailing list. Thanks!
Thanks for comment.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder the columns like "Business Strategy" and "Company Description" also can be detected.
How about that idea?