使用python对xml文件中的子元素进行缩进

2024-06-17 12:52:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个XML文件:

<ns0:component xmlns:ns0="http://www.accellera.org/XMLSchema/IPXACT/1685- 
2014" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.accellera.org/XMLSchema/IPXACT/1685-2014 
http://www.accellera.org/XMLSchema/IPXACT/1685-2014/index.xsd">
    <ns0:vendor>spiritconsortium.org</ns0:vendor>
    <ns0:library>Leon2RTL</ns0:library>
    <ns0:name>ahbbus12</ns0:name>
<ns0:circuitFunctionDescriptions><ns0:name>PLL</ns0:name> 
</ns0:circuitFunctionDescriptions></ns0:component>

但我想要一张漂亮的表格,比如:

<ns0:component xmlns:ns0="http://www.accellera.org/XMLSchema/IPXACT/1685- 
    2014" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.accellera.org/XMLSchema/IPXACT/1685-2014 
    http://www.accellera.org/XMLSchema/IPXACT/1685-2014/index.xsd">
    <ns0:vendor>spiritconsortium.org</ns0:vendor>
    <ns0:library>Leon2RTL</ns0:library>
    <ns0:name>ahbbus12</ns0:name>
    <ns0:circuitFunctionDescriptions>
       <ns0:name>PLL</ns0:name> 
    </ns0:circuitFunctionDescriptions>
</ns0:component>

我需要将其保存为一个输出文件(我的意思是我需要将结果保存在另一个xml文件中,而不仅仅是打印它)。我想知道我该怎么做


Tags: 文件nameorghttpwwwlibrarycomponentxmlschema
1条回答
网友
1楼 · 发布于 2024-06-17 12:52:33

大多数具有漂亮打印缩进功能的序列化程序将提供类似于您所寻求的元素缩进的内容。请参见Pretty printing XML in Python,因为您已将问题标记为

有些还会提供属性缩进

但是,没有一个会像在所需的XML中那样破坏属性值,因为一般来说,在属性值中添加空格是不可能的,并且仍然可以确保语义将被保留

你可以在你的例子中看到这一点

这个名称空间声明(即使我们很慷慨并从源文档修复它)

xmlns:ns0="http://www.accellera.org/XMLSchema/IPXACT/1685-2014"

不等于

    xmlns:ns0="http://www.accellera.org/XMLSchema/IPXACT/1685- 
    2014"

相关问题 更多 >