python and parsing an xml file

Stefan Behnel stefan_ml at behnel.de
Tue Feb 22 02:04:53 EST 2011


Matt Funk, 21.02.2011 23:40:
> On 2/21/2011 3:28 PM, Stefan Behnel wrote:
>> Matt Funk, 21.02.2011 23:07:
>>> thank you for your advice.
>>> I am running into an issue though (which is likely a newbie problem):
>>>
>>> My xml file looks like (which i got from the internet):
>>> <?xml version="1.0"?>
>>> <catalog>
>>>      <book id="bk101">
>>>         <author>Gambardella, Matthew</author>
>>>         <title>XML Developer's Guide</title>
>>>         <genre>Computer</genre>
>>>         <price>44.95</price>
>>>         <publish_date>2000-10-01</publish_date>
>>>         <description>An in-depth look at creating applications
>>>         with XML.</description>
>>>      </book>
>>> </catalog>
>>>
>>> Then i try to access it as:
>>>
>>> from lxml import etree
>>> from lxml import objectify
>>>
>>> inputfile="../input/books.xml"
>>> parser = etree.XMLParser(ns_clean=True)
>>> parser = etree.XMLParser(remove_comments=True)
>>
>> Change that to
>>
>> parser = objectify.makeparser(ns_clean=True, remove_comments=True)
>>
>>> root = objectify.parse(inputfile,parser)
>>
>> Change that to
>>
>> root = objectify.parse(inputfile,parser).getroot()
>
> According to your instructions i do:
>
> parser = objectify.makeparser(ns_clean=True, remove_comments=True)
> root = objectify.parse(inputfile,parser).getroot()
> print root.catalog.book.author.text

root == <catalog>

Try "print root.tag", and read the tutorial.

Stefan




More information about the Python-list mailing list