I am trying to figure out how to turn some XML into a nice readable statement. I am currently using Nokogiri, and have become stuck while trying to do the following:
I want to convert the following:
<baz>
<option id="foo">Hello</option>
<option id="bar">World</option>
</baz>
into the following:
baz has options: 'Foo' = 'Hello', 'Bar' = 'World'
I am currently using the following code to achieve this, but I feel like there must be a better way using join, and I can’t seem to figure it out.
optText = "baz has options:"
baznode.xpath("option").each { |opt|
optText << "'#{opt.xpath("@id").text}' = '#{opt.text}', "
}
optText << args[0..-3] << "\n"
Any suggestions?
Other than maybe using
collect/joinI don’t see much benefit in mucking with it.I might change the output to be something more like:
But that depends entirely on your needs, of course. Scanning across a line might be a bit difficult if there are a lot of options, but if they’re aren’t, the original is probably easier to parse mentally.
If you’re doing this all over the place with multiple “things” it might make sense to transform it all into JSON/YAML and just dump that, unless you want really human-readable text.