1

the following does not appear to parse the xml data correctly or is doing something wrong.

This is the code being run.

from lxml import etree from lxml.etree import fromstring

if request.POST:

    xml = request.POST['xml'].encode('utf-8')
    parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8')
    h = fromstring(xml, parser=parser)
    status = h.cssselect('itagg_delivery_receipt status').text_content()
    return HttpResponse(status)

The error:

AttributeError: 'lxml.etree._Element' object has no attribute 'cssselect' status

This is the xml document that is being sent:

 <?xml version="1.1" encoding="ISO-8859-1"?>
<itagg_delivery_receipt>
<version>1.0</version>
<msisdn>447889000000</msisdn>
<submission_ref>
845tgrgsehg394g3hdfhhh56445y7ts6</
submission_ref>
<status>Delivered</status>
<reason>4</reason>
<timestamp>20050709120945</timestamp>
<retry>0</retry>
</itagg_delivery_receipt> 

I have dumped out str(h) and it looks like this <element 0x7fd341e93870="" at="" itagg_delivery_receipt=""></element>

1
  • i don't think you can use cssselect on an xml doc. If you import from lxml.html you get cssselect, but i don't know if that's appropriate for your XML file. Commented Jun 20, 2013 at 16:51

2 Answers 2

1

Here's how to get the thing you want with xpath:

>>> h.xpath('status/text()')
['Delivered']

So with a little helper function in your code:

def first(seq,default=None):
  for item in seq:
    return item
  return default

...

status = first(h.xpath('status/text()'))
Sign up to request clarification or add additional context in comments.

Comments

0

Before using cssselect you need to install it

pip install cssselect

3 Comments

There's a cssselect module in the lxml library the OP is using.
@MattH Just reread csssellect.py from lxml and found "This is a thin wrapper around cssselect 0.7 or later."
@MattH lxml added another obstacle (there's a surprise..) by removing its built-in cssselect and using an external one, meaning you have to install it separately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.