1

我收到一个名为 xml 的参数,其中包含一个 xml 文档。这是我尝试过的......

from lxml.cssselect import CSSSelector, etree
from lxml.etree import fromstring

if request.POST:

    parser = etree.XMLParser(ns_clean=True, recover=True)
    h = etree.parse(request.POST['xml'], parser)

    return HttpResponse(h)

但我收到此错误:

[Fri Apr 05 09:50:13 2013] [error] IOError: Error reading file '<?xml version="1.0" encoding="ISO-8859-1"?>
[Fri Apr 05 09:50:13 2013] [error] <delivery_receipt>
[Fri Apr 05 09:50:13 2013] [error]     <version>1.1</version>
[Fri Apr 05 09:50:13 2013] [error]     <msisdn>447777111111</msisdn>
[Fri Apr 05 09:50:13 2013] [error]     <submission_ref>12345678901234567890123456789012</submission_ref>
[Fri Apr 05 09:50:13 2013] [error]     <status>Delivered</status>
[Fri Apr 05 09:50:13 2013] [error]     <reason>4</reason>
[Fri Apr 05 09:50:13 2013] [error]     <gmt_timestamp>20130405095100</gmt_timestamp>
[Fri Apr 05 09:50:13 2013] [error]     <retry>0</retry>
[Fri Apr 05 09:50:13 2013] [error] </delivery_receipt>': failed to load external entity "<?xml version="1.0" encoding="ISO-8859-1"?>
[Fri Apr 05 09:50:13 2013] [error] <delivery_receipt>
[Fri Apr 05 09:50:13 2013] [error]     <version>1.1</version>
[Fri Apr 05 09:50:13 2013] [error]     <msisdn>447777111111</msisdn>
[Fri Apr 05 09:50:13 2013] [error]     <submission_ref>12345678901234567890123456789012</submission_ref>

ETC

有任何想法吗?谢谢 :)

4

2 回答 2

1

request.POST默认情况下返回 unicode 字符串。您遇到的下一个问题与您提供的编码与您提供的文档中声明的编码不匹配有关。

doc = request.POST.get('xml','')
if not doc:
  raise Exception()
h = etree.XML(doc.encode('ascii'), parser)
于 2013-04-05T09:08:37.430 回答
1

etree.parse需要一个文件名(或文件对象)。没有文件名为<all your xml>.

您需要将 XML 提供给解析器:

from lxml.cssselect import CSSSelector, etree
from lxml.etree import fromstring

if request.POST:

    parser = etree.XMLParser(ns_clean=True, recover=True)
    parser.feed(request.POST['xml'])
    h = parser.close()
    ...

或使用fromstringXML功能。

h = fromstring(request.POST['xml'], parser=parser)

或者

h = etree.XML(request.POST['xml'], parser=parser)

lxml.etree 教程

于 2013-04-05T09:08:43.460 回答