【问题标题】:etree.ElementTree add tag attribute with special charetree.ElementTree 添加带有特殊字符的标签属性
【发布时间】:2018-05-16 11:44:49
【问题描述】:

我想生成带有属性 xsi:noNamespaceSchemaLocation 的元素。

<Test name="Name" xsi:noNamespaceSchemaLocation="anyURI"></a>

我的python代码

import xml.etree.ElementTree as xml
root = xml.Element('Tests', xsi:noNamespaceSchemaLocation="anyURI")

当我尝试运行 python 文件时。报错

文件“.../xml-generator.py”,第 4 行 root = xml.Element('Tests', xsi:noNamespaceSchemaLocation="anyURI") ^ SyntaxError: 无效语法

【问题讨论】:

    标签: xml python-3.x xml-parsing


    【解决方案1】:

    你可以稍后通过Element.set设置属性:

    root = xml.Element("Tests")
    root.set("xsi:noNamespaceSchemaLocation", "anyURI")
    

    或者您可以先将 Element 的 kwargs 打包到字典中,然后使用 ** 运算符直接再次解包:

    root = xml.Element("Tests", **{"xsi:noNamespaceSchemaLocation" : "anyURI"})
    

    【讨论】:

      猜你喜欢
      • 2014-06-07
      • 2022-01-07
      • 2021-03-06
      • 2016-06-19
      • 2021-11-10
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多