how to parse xml in web2py?

907 views
Skip to first unread message

Amit

unread,
Aug 23, 2012, 5:53:32 AM8/23/12
to web...@googlegroups.com
Hi,
I have web service method in my application which will receive xml file from the request, i need to parse it and save the extracted data to the database. Please suggest me the best way to parse xml in web2py.

xml format would be like below:

<?xml version='1.0' encoding='utf-8'?>
<macaddress value="00:00:00:00:00:00" >
  <devicetype value="abc">
    <deviceserialno>123456</sensorserialno>
    <mfgdate>2012-06-30</mngdate>
    <mfgsiteid>1</mngsiteid>
    <secretkey>adadafdfdgfgfhggjghjjj</secretkey>
  </sensortype>
</macaddress>

David Marko

unread,
Aug 23, 2012, 7:35:43 AM8/23/12
to web...@googlegroups.com
Did you consider to use  http://docs.python.org/library/xml.etree.elementtree.html ?

Dne čtvrtek, 23. srpna 2012 11:53:32 UTC+2 Amit napsal(a):

Anthony

unread,
Aug 23, 2012, 9:59:25 AM8/23/12
to web...@googlegroups.com
For simple parsing, you can also use the built-in TAG() helper -- see http://web2py.com/books/default/chapter/29/5#Parsing.

FYI, in your example, some of the closing tags do not match their associated opening tags.

Anthony

Mike Girard

unread,
Aug 23, 2012, 10:54:47 AM8/23/12
to web...@googlegroups.com
ElementTree or cElementTree are good. CElementTree is said to be faster.

The most important thing is the method you use. If your sample is the extent of the document, any parser will do. However, if your actual documents are large, you should consider an iterparsing method to conserve memory.

I think the most robust parser in terms of methods is lxml, which supports XSL and XPath along with ElementTrees. However, it requires separate installation. Python ships with ElementTree and cElementTree which are fine for most cases.

villas

unread,
Aug 23, 2012, 11:18:37 AM8/23/12
to web...@googlegroups.com
If the XML is not well-formed, take a look at beautiful soup.   I have never found a parser so tolerant and forgiving.

Amit

unread,
Aug 23, 2012, 10:43:21 PM8/23/12
to web...@googlegroups.com
Thanks guys for helping me to write xml parsing in python..I will use ElementTree Or cElementTree to extract data from xml and let you people know about the outcome.

@Anthony: My mistatke :( , I manually written the xml so did mistake on matching opening and closing tags.

Thanks once again
Amit

--
 
 
 

Reply all
Reply to author
Forward
0 new messages