【发布时间】:2016-12-04 10:18:02
【问题描述】:
我有一个以下格式的 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<foo>
<bar>
<bat>1</bat>
</bar>
<a>
<b xmlns="urn:schemas-microsoft-com:asm.v1">
<c>1</c>
</b>
</a>
</foo>
我想把bat的值改成'2',把文件改成这样:
<?xml version="1.0" encoding="utf-8"?>
<foo>
<bar>
<bat>2</bat>
</bar>
<a>
<b xmlns="urn:schemas-microsoft-com:asm.v1">
<c>1</c>
</b>
</a>
</foo>
我通过这样做打开这个文件
tree = ET.parse(filePath)
root = tree.getroot()
然后我将 bat 的值更改为 '2' 并像这样保存文件:
tree.write(filePath, "utf-8", True, None, "xml")
bat 的值成功更改为 2,但是 XML 文件现在看起来像这样。
<?xml version="1.0" encoding="utf-8"?>
<foo xmlns:ns0="urn:schemas-microsoft-com:asm.v1">
<bar>
<bat>2</bat>
</bar>
<a>
<ns0:b>
<ns0:c>1</ns0:c>
</ns0:b>
</a>
</foo>
为了解决命名空间命名为 ns0 的问题,我在解析文档之前做了以下操作
ET.register_namespace('', "urn:schemas-microsoft-com:asm.v1")
这摆脱了 ns0 命名空间,但 xml 文件现在看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<foo xmlns="urn:schemas-microsoft-com:asm.v1">
<bar>
<bat>2</bat>
</bar>
<a>
<b>
<c>1</c>
</b>
</a>
</foo>
我该怎么做才能得到我需要的输出?
【问题讨论】:
-
你使用的是什么版本的 Python 和 lxml?我无法重现这种行为。
tree.write(filePath, "utf-8", True, None, "xml")在 Python 3.5 上抛出错误——尝试明确地做你的参数:tree.write("output.xml",xml_declaration=True,encoding="utf-8",pretty_print=True) -
我使用的是 Python 3.5.1 版。不确定 lxml 是什么——我昨天开始使用 Python。
-
我试过了,明确指定参数没有区别。
-
非常类似于这个问题:stackoverflow.com/q/38438921/407651
-
如果您可以使用不在标准库中的工具包,请查看 lxml。它类似于 ElementTree(相同基本 API 的扩展),但功能更强大。 lxml.de
标签: python xml elementtree