XSLT is the perfect tool for transforming one XML structure into another.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- copy the root element and handle its <car> children -->
<xsl:template match="/root">
<xsl:copy>
<xsl:apply-templates select="car" />
<xsl:copy>
</xsl:template>
<!-- car elements become a container for their properties -->
<xsl:template match="car">
<car name="{normalize-space()}">
<!-- ** see 1) -->
<xsl:copy-of select="following-sibling::color[1]" />
<xsl:copy-of select="following-sibling::speed[1]" />
</car>
</xsl:template>
</xsl:stylesheet>
1) For this to work, your XML has to have a <color>
and a <speed>
for every <car>
. If that's not guaranteed, or number and kind of properties is generally variable, replace the two lines with the generic form of the copy statement:
<!-- any following-sibling element that "belongs" to the same <car> -->
<xsl:copy-of select="following-sibling::*[
generate-id(preceding-sibling::car[1]) = generate-id(current())
]" />
Applied to your XML (I implied a document element named <root>
), this would be the result
<root>
<car name="Ferrari">
<color>red</color>
<speed>300</speed>
</car>
<car name="Porsche">
<color>black</color>
<speed>310</speed>
</car>
</root>
Sample code that applies XSLT to XML in Python should be really easy to find, so I omit that here. It'll be hardly more than 4 or five lines of Python code.