无法使用默认命名空间编写XML文件

And*_*mar 10 python xml elementtree

我正在编写一个Python脚本来更新Visual Studio项目文件.它们看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" 
      xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
      ...
Run Code Online (Sandbox Code Playgroud)

以下代码读取然后写入文件:

import xml.etree.ElementTree as ET

tree = ET.parse(projectFile)
root = tree.getroot()
tree.write(projectFile,
           xml_declaration = True,
           encoding = 'utf-8',
           method = 'xml',
           default_namespace = "http://schemas.microsoft.com/developer/msbuild/2003")
Run Code Online (Sandbox Code Playgroud)

Python在最后一行抛出错误,说:

ValueError: cannot use non-qualified names with default_namespace option
Run Code Online (Sandbox Code Playgroud)

这是令人惊讶的,因为我只是在阅读和写作,中间没有编辑.Visual Studio拒绝加载没有默认命名空间的XML文件,因此省略它不是可选的.

为什么会出现此错误?建议或替代方案欢迎.

Wom*_*tPM 31

这与使用ElementTree保存XML文件重复

解决方案是在解析项目文件之前定义默认命名空间.

ET.register_namespace('',"http://schemas.microsoft.com/developer/msbuild/2003")
Run Code Online (Sandbox Code Playgroud)

然后把你的文件写出来

tree.write(projectFile,
           xml_declaration = True,
           encoding = 'utf-8',
           method = 'xml')
Run Code Online (Sandbox Code Playgroud)

您已成功完成文件的往返.并避免在任何地方创建ns0标记.

  • 这种方法有效。但是,“find('mytag', ns)”和“findall('mytag', ns)”方法失败(它们返回空元素列表)。似乎它们需要一个*非空*命名空间名称。这很好,除非您想使用默认命名空间中的元素的空命名空间前缀来“write()” XML 文件。(使用Python 2.7。) (2认同)