我有一个这样的 xml 文件:
<car>Ferrari</car>
<color>red</color>
<speed>300</speed>
<car>Porsche</car>
<color>black</color>
<speed>310</speed>
我需要这种形式:
<car name="Ferrari">
<color>red</color>
<speed>300</speed>
</car>
<car name="Porsche">
<color>black</color>
<speed>310</speed>
</car>
我该怎么做?我正在苦苦挣扎,因为我想不出一种方法来从原始 xml 文件中的标签的平面列表中创建我需要的结构。
我选择的语言是 Python,但欢迎提出任何建议。
请您参考如下方法:
XSLT 是将一种 XML 结构转换为另一种 XML 结构的完美工具。
<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) 为此,您的 XML 必须具有 <color>和一个 <speed>对于每个 <car> .如果不能保证,或者属性的数量和种类通常是可变的,请将这两行替换为复制语句的通用形式:
<!-- 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())
]" />
应用于您的 XML(我暗示了一个名为 <root> 的文档元素),这将是结果
<root>
<car name="Ferrari">
<color>red</color>
<speed>300</speed>
</car>
<car name="Porsche">
<color>black</color>
<speed>310</speed>
</car>
</root>
在 Python 中将 XSLT 应用于 XML 的示例代码应该很容易找到,所以我在这里省略。它不会超过 4 或 5 行 Python 代码。
