2

我正在尝试在 Python 2.7 中使用 lxml 解析Evernote 标记语言(ENML)。ENML 是 XHTML 的超集。

from StringIO import StringIO
import lxml.etree as etree

if __name__ == '__main__':
    xml_str = StringIO('<?xml version="1.0" encoding="UTF-8"?>\r\n<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">\r\n\r\n<en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">\nA really simple example. &nbsp;Another sentence.\n</en-note>')
    tree = etree.parse(xml_str)

上面的代码出错了:

XMLSyntaxError: Entity 'nbsp' not defined, line 5, column 32

如何成功解析 ENML?

4

2 回答 2

3

&nbsp;由 HTML 解析器而非 XML 解析器理解:

from StringIO import StringIO
import lxml.html as LH
if __name__ == '__main__':
    xml_str = StringIO('<?xml version="1.0" encoding="UTF-8"?>\r\n<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">\r\n\r\n<en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">\nA really simple example. &nbsp;Another sentence.\n</en-note>')
    tree = LH.parse(xml_str)
    print(LH.tostring(tree))
于 2013-02-27T02:10:55.223 回答
0

您可以尝试将实体名称替换为其数值。

http://www.w3schools.com/tags/ref_entities.asp

于 2013-02-27T04:08:24.347 回答