Wednesday, 7 January 2015

How to eliminate duplicate XML namespace definitions?



I often come across XML where the same namespace is defined multiple times, instead of only at a parent element of the elements where it is needed.


Is there a simple method/tool for extracting all namespace definitions in an XML and relocating each of these definitions to a node such that each namespace is defined only once? Preferably also with an option for all nodes to be prefixed with their namespace (rather than using a default namespace from some parent). I find this would yield more human readable XML.


As an example, how could one automatically translate this



<m:Albums xmlns:m="http://ift.tt/1wqb3QJ">
<m:Album xmlns:m="http://ift.tt/1wqb3QJ">
<m:Artist xmlns:m="http://ift.tt/1wqb3QJ">
<c:Name xmlns:c="http://ift.tt/1DkCl2v">
Sting
</c:Name>
</m:Artist>
<m:Title>
Mercury Falling
</m:Title>
</m:Album>
<Album xmlns="http://ift.tt/1wqb3QJ">
<Artist>
<c:Name xmlns:c="http://ift.tt/1DkCl2v">
Maria Mena
</c:Name>
</Artist>
<Title xmlns="http://ift.tt/1wqb3QJ">
Weapon in Mind
</Title>
</Album>
</m:Albums>


into this?



<m:Albums xmlns:m="http://ift.tt/1wqb3QJ" xmlns:c="http://ift.tt/1DkCl2v">
<m:Album>
<m:Artist>
<c:Name>
Sting
</c:Name>
</m:Artist>
<m:Title>
Mercury Falling
</m:Title>
</m:Album>
<m:Album>
<m:Artist>
<c:Name>
Maria Mena
</c:Name>
</m:Artist>
<m:Title>
Weapon in Mind
</m:Title>
</m:Album>
</m:Albums>

No comments:

Post a Comment