在使用python的xml.etree模块时,我如何转义xml--例如‘'>’‘和'<’这样的特殊字符,以便在标记中使用?我必须手动这样做吗?埃特里有没有我所缺少的方法或权杖?
考虑:
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></<>发布于 2017-01-23 16:01:24
在这里,我希望看到这样的章节:
<<><a>b</a></<>
这不是格式良好的XML。我想你忘了分号,但是加分号没有帮助。下列情况也是不正确的:
<<><a>b</a></<>在代码中,您试图创建名为<、>和=的元素。那不管用。在XML元素名称中禁止使用以下所有内容:<、>、=、>、<。
不幸的是,ElementTree有点松懈,允许您创建伪XML,如下所示:
<filter type="test"><<><a>b</a></<><>><a>b</a></>><=><a>b</a></=></filter>如果您使用的是lxml.etree (参见http://lxml.de)而不是xml.etree.ElementTree,您将收到一条错误消息:"ValueError:无效标签名u'<'“。
发布于 2017-01-22 23:50:03
<和>在XML中是无效字符,应该分别用<和>代替。
可以使用正则表达式替换无效字符:
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>'虽然代码涉及的范围更长一些,但它是一种非常有效的替换方法。
https://stackoverflow.com/questions/41797005
复制相似问题