无法使用默认名称空间写入XML文件 [英] Cannot write XML file with default namespace

查看:125
本文介绍了无法使用默认名称空间写入XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a Python script to update Visual Studio project files. They look like this:

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

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

The following code reads and then writes the file:

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")

Python抛出最后一行错误,提示:

Python throws an error at the last line, saying:

ValueError: cannot use non-qualified names with default_namespace option

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

This is surprising since I'm just reading and writing, with no editing in between. Visual Studio refuses to load XML files without a default namespace, so omitting it is not optional.

为什么会发生此错误?欢迎提出建议或替代方案。

Why does this error occur? Suggestions or alternatives welcome.

推荐答案

这是使用ElementTree保存XML文件

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

The solution is to define your default namespace BEFORE parsing the project file.

ET.register_namespace('',"http://schemas.microsoft.com/developer/msbuild/2003")

然后将文件写为

tree.write(projectFile,
           xml_declaration = True,
           encoding = 'utf-8',
           method = 'xml')

您已成功往返文件。并且避免到处都创建ns0标签。

You have successfully round-tripped your file. And avoided the creation of ns0 tags everywhere.

这篇关于无法使用默认名称空间写入XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆