Python xml.etree 转义
Python xml.etree escaping
当使用 python 的 xml.etree 模块时,我如何转义 xml- 特殊字符,如“>”和“<”以用于标签内?我必须手动这样做吗? etree 是否有我缺少的方法或 kwarg?
考虑:
In [1]: from xml.etree.ElementTree import Element, SubElement, tostring
In [2]: root = Element('filter')
In [3]: root.set('type', 'test')
In [4]: for op in ['<', '>', '=']:
...: sub_elem = SubElement(root, op)
...: child = Element('a')
...: child.text = 'b'
...: sub_elem.append(child)
...:
In [5]: tostring(root)
Out[5]: '<filter type="test"><<><a>b</a></<><>><a>b</a></>><=><a>b</a></=></filter>'
我希望看到的部分如下:
<<><a>b</a></<>
<
和 >
是 XML 中的 not valid characters,应分别替换为 <
和 >
。
您可以使用正则表达式替换无效字符:
import re
regexp = re.compile(r'<|>') # here we are making a regex to catch either the character '<' or '>'
replacement_map = {'<': '<', '>': '>'} # a dict to map a character to the replacement value.
regexp.sub(lambda match: replacement_map[match.group(0)], '<a>hello</a>') # do the replacement
# output: '<a>hello</a>'
虽然代码有点复杂,但这是一种非常有效的替换方式。
Where I would like to see sections like:
<<><a>b</a></<>
这不是 well-formed XML。我猜你忘记了分号,但添加分号也无济于事。下面也是ill-formed:
<<><a>b</a></<>
在代码中,您尝试创建名为 <
、>
和 =
的元素。那行不通的。 XML 元素名称中禁止使用以下所有内容:<
、>
、=
、>
、<
。
不幸的是,ElementTree 有点松懈,允许您创建 pseudo-XML,例如这个(来自问题):
<filter type="test"><<><a>b</a></<><>><a>b</a></>><=><a>b</a></=></filter>
如果您使用 lxml.etree
(参见 http://lxml.de)而不是 xml.etree.ElementTree
,您将收到一条错误消息:"ValueError: Invalid tag name u'<'".
当使用 python 的 xml.etree 模块时,我如何转义 xml- 特殊字符,如“>”和“<”以用于标签内?我必须手动这样做吗? etree 是否有我缺少的方法或 kwarg?
考虑:
In [1]: from xml.etree.ElementTree import Element, SubElement, tostring
In [2]: root = Element('filter')
In [3]: root.set('type', 'test')
In [4]: for op in ['<', '>', '=']:
...: sub_elem = SubElement(root, op)
...: child = Element('a')
...: child.text = 'b'
...: sub_elem.append(child)
...:
In [5]: tostring(root)
Out[5]: '<filter type="test"><<><a>b</a></<><>><a>b</a></>><=><a>b</a></=></filter>'
我希望看到的部分如下:
<<><a>b</a></<>
<
和 >
是 XML 中的 not valid characters,应分别替换为 <
和 >
。
您可以使用正则表达式替换无效字符:
import re
regexp = re.compile(r'<|>') # here we are making a regex to catch either the character '<' or '>'
replacement_map = {'<': '<', '>': '>'} # a dict to map a character to the replacement value.
regexp.sub(lambda match: replacement_map[match.group(0)], '<a>hello</a>') # do the replacement
# output: '<a>hello</a>'
虽然代码有点复杂,但这是一种非常有效的替换方式。
Where I would like to see sections like:
<<><a>b</a></<>
这不是 well-formed XML。我猜你忘记了分号,但添加分号也无济于事。下面也是ill-formed:
<<><a>b</a></<>
在代码中,您尝试创建名为 <
、>
和 =
的元素。那行不通的。 XML 元素名称中禁止使用以下所有内容:<
、>
、=
、>
、<
。
不幸的是,ElementTree 有点松懈,允许您创建 pseudo-XML,例如这个(来自问题):
<filter type="test"><<><a>b</a></<><>><a>b</a></>><=><a>b</a></=></filter>
如果您使用 lxml.etree
(参见 http://lxml.de)而不是 xml.etree.ElementTree
,您将收到一条错误消息:"ValueError: Invalid tag name u'<'".