有没有办法在 python 中创建一个 xml 元素,并在其字符串中包含特殊字符?

Is there a way to create an xml element in python with special characters in its string?

我正在编写一个 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”这样的名字时,我得到一个异常:

not well-formed (invalid token): line 1, column XYZ

没有。 '/' 字符是 not allowed in XML element names。一种可能的解决方案是在元素的属性中保留 foobar/2_barfoo 之类的字符串,例如:

<myelement name="foobar/2_barfoo">...</myelement>