I'm working with some XML that involves multiple namespaces (specifically ResourceSync, which embeds namespaced tags in Sitemap documents).
When I create REXML elements, I can set a global namespace:
foo = REXML::Element.new('foo')
foo.add_namespace('http://foo.com/')
puts foo # outputs <foo xmlns='http://foo.com/'/>
and I can create a namespace with a prefix:
foo.add_namespace('bar', 'http://bar.org/')
puts foo # outputs <foo xmlns:bar='http://bar.org/' xmlns='http://foo.com/'/>
However, if I then add another element with the same namespace URI as the prefix, but without explicitly using the prefix --
bar = REXML::Element.new('bar')
bar.add_namespace('http://bar.org/')
foo.add_element(bar)
-- REXML isn't smart enough to note the presence of the prefix and use it. Instead of the expected
<foo xmlns:bar='http://bar.org/' xmlns='http://foo.com/'>
<bar:bar/>
</foo>
I get the needlessly verbose:
<foo xmlns:bar='http://bar.org/' xmlns='http://foo.com/'>
<bar xmlns='http://bar.org/'/>
</foo>
I could work around this by ignoring namespace URIs entirely and just hacking the prefix into the element name:
baz = REXML::Element.new('bar:baz')
foo.add_element(baz)
However, at the time the element is created, the only thing I know for certain is the namespace URI -- I don't know what parent element it's going to be added to or what namespace prefixes might exist there. (And namespace prefixes aren't really part of the logical document model anyway, while namespace URIs are.)
Is there a way to get REXML to resolve the prefixes at output time, and/or a straightforward way to postprocess the REXML document to use the prefixes?
Note that I'm not looking for e.g. a Nokogiri solution, since I'm using a library, xml-mapping that uses REXML internally (as it happens, it also doesn't seem to have any concept of namespaces, but I've figured out a way to work around that).