我有以下格式的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>
Run Code Online (Sandbox Code Playgroud)
我想将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>
Run Code Online (Sandbox Code Playgroud)
我这样做来打开这个文件
tree = ET.parse(filePath)
root = tree.getroot()
Run Code Online (Sandbox Code Playgroud)
然后,将bat的值更改为'2'并保存如下文件:
tree.write(filePath, "utf-8", True, None, "xml")
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
为了解决拥有名为ns0的命名空间的问题,在解析文档之前,请执行以下操作
ET.register_namespace('', "urn:schemas-microsoft-com:asm.v1")
Run Code Online (Sandbox Code Playgroud)
这摆脱了ns0 namepace,但是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>
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能获得所需的输出?
我使用xmlPython3.5中的库来读取和编写 xml文件.我不修改文件.只是打开并写.但是库修改了文件.
这是示例文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<movie>
<title>Der Eisbär</title>
<ids>
<entry>
<key>tmdb</key>
<value xsi:type="xs:int" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">9321</value>
</entry>
<entry>
<key>imdb</key>
<value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">tt0167132</value>
</entry>
</ids>
</movie>
Run Code Online (Sandbox Code Playgroud)
这是代码
import xml.etree.ElementTree as ET
tree = ET.parse('x.nfo')
tree.write('y.nfo', encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)
而xml文件就变成了这个
<movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<title>Der Eisbär</title>
<ids>
<entry>
<key>tmdb</key>
<value xsi:type="xs:int">9321</value>
</entry>
<entry>
<key>imdb</key>
<value xsi:type="xs:string">tt0167132</value>
</entry>
</ids>
</movie>
Run Code Online (Sandbox Code Playgroud)
<movie>2行中的-tag现在具有属性.<value>7行和第11行中的-tag现在具有较少的属性.