lxml:强制将换行符转换为实体

lxml: Force to convert newlines to entities

有没有办法将文本元素内的换行符输出为 
 实体? 目前,换行符按原样插入到输出中:

from lxml import etree
from lxml.builder import E
etree.tostring(E.a('one\ntwo'), pretty_print=True)
b'<a>one\ntwo</a>\n'

期望的输出:

b'<a>one&#13;two</a>\n'

查看 lxml docs 后,似乎无法强制将某些字符打印为转义实体。看起来转义的字符列表也因输出编码而异。

综上所述,我会在 lxml 之上使用 BeautifulSoup's prettify() 来完成工作:

from bs4 import BeautifulSoup as Soup
from xml.sax.saxutils import escape

def extra_entities(s):
    return escape(s).replace('\n', '&#13;')

soup = Soup("<a>one\ntwo</a>", 'lxml-xml')
print(soup.prettify(formatter=extra_entities))

输出:

<?xml version="1.0" encoding="utf-8"?>
<a>
 one&#10;two
</a>

请注意,换行符实际上应该映射到 &#10;&#13; 用于运输 returns 或 \r)但我不会争论,因为我无法测试本地 FCPXML 格式。