我有下一个XML:

data3.xml:

<?xml version="1.0" encoding="UTF-8"?>
<feed
    xmlns="http://www.w3.org/2005/Atom">
    <entry>
        <content>
            <ns2:executionresult
                xmlns:ns2="http://jazz.net/xmlns/alm/qm/v0.1/"
                xmlns:ns4="http://purl.org/dc/elements/1.1/">
                <ns4:title>xxx</ns4:title>
            </ns2:executionresult>
        </content>
    </entry>
</feed>

我有下一个代码:

test3.py:

import xml.etree.ElementTree as ET
tree = ET.parse('data3.xml')
root = tree.getroot()
xml_str = ET.tostring(root).decode()
print(xml_str)

Output:

$ python3 test3.py
<ns0:feed xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:ns0="http://www.w3.org/2005/Atom" xmlns:ns1="http://jazz.net/xmlns/alm/qm/v0.1/">
    <ns0:entry>
        <ns0:content>
            <ns1:executionresult>
                <dc:title>xxx</dc:title>
            </ns1:executionresult>
        </ns0:content>
    </ns0:entry>
</ns0:feed>

我想知道为什么ElementTree会自动为我更改namespace?规则是什么?我怎么才能避免它呢?

推荐答案

请使用lxml库而不是xml.etree

代码:

from lxml import etree

tree = etree.parse('data3.xml')
root = tree.getroot()
xml_str = etree.tostring(root, pretty_print=True, encoding='utf-8').decode()
print(xml_str)

输出:

<feed xmlns="http://www.w3.org/2005/Atom">
    <entry>
        <content>
            <ns2:executionresult xmlns:ns2="http://jazz.net/xmlns/alm/qm/v0.1/" xmlns:ns4="http://purl.org/dc/elements/1.1/">
                <ns4:title>xxx</ns4:title>
            </ns2:executionresult>
        </content>
    </entry>
</feed>

Python相关问答推荐

如何在Python中使用ijson解析SON期间检索文件位置?

基本链合同的地址是如何计算的?

使用多个性能指标执行循环特征消除

Python plt.text中重叠,包adjust_text不起作用,如何修复?

try 与gemini-pro进行多轮聊天时出错

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

如何获得每个组的时间戳差异?

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

在vscode上使用Python虚拟环境时((env))

计算每个IP的平均值

不能使用Gekko方程'

用砂箱开发Web统计分析

如何在Python中获取`Genericums`超级类型?

处理具有多个独立头的CSV文件

递归函数修饰器

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

Regex用于匹配Python中逗号分隔的AWS区域

按条件计算将记录拆分成两条记录

将相应的值从第2列合并到第1列(Pandas )

如果列包含空值,则PANAS查询不起作用