【发布时间】:2019-07-23 08:39:51
【问题描述】:
我正在编写一个小 Python 工具来帮助我组织和分析一些数据。不幸的是,某些数据包含某些似乎在 xml 元素中不起作用的字符(例如'/')
有没有办法将这些信息保存在字符串中,并且仍然使用该名称创建一个 xml 元素?
替换字符会改变数据并使其部分无法使用
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
class Rule:
name: str
rule_type: str
usage: list
macros: list
features: list
local_functions: list
local_variables: list
return_value: str
info: str
def __init__(self, name, rule_type, usage, macros, features, local_functions, local_variables, return_value, info):
self.name = name
self.rule_type = rule_type
self.usage = [elem for elem in usage]
self.macros = [elem for elem in macros]
self.features = [elem for elem in features]
self.local_functions = local_functions
self.local_variables = [elem for elem in local_variables]
self.return_value = return_value
self.info = info
def rule_to_xml(self):
root = Element(self.name)
root.append(Comment(self.info))
当输入像“foobar/2_barfoo”这样的名字时,我得到一个例外:
格式不正确(无效标记):第 1 行,XYZ 列
【问题讨论】:
-
您是否尝试过使用 UTF-8 编码?
-
据我了解 XmlEtree 在 python 中的 xml 使用情况,如果没有另外指定,使用 utf-8 是标准的吗?
标签: python xml elementtree