[lxml-dev] Parsing Received XML: Getting Childs and Assign
Stefan Behnel
stefan_ml at behnel.de
Sat Apr 7 18:11:37 CEST 2007
Hi,
Ram Peters wrote:
> <Library>
> <DVD id="1">
> <title>Breakfast at Tiffany's</title>
> <format>Movie</format>
> <genre>Classic</genre>
> </DVD>
>
> <DVD id="2">
> <title>Borat</title>
> <format>Movie</format>
> <genre>Comedy</genre>
> </DVD>
> </Library>
>
> How to parse this xml received from a client using lxml?
> I will be using lxml objectify.
At the end of this section in the docs, you will find the command that does it:
http://codespeak.net/lxml/dev/objectify.html#creating-objectify-trees
namely:
>>> root = objectify.fromstring("<test/>")
Or, if you want to parse from a file, set up a parser as this section describes
http://codespeak.net/lxml/dev/objectify.html#setting-up-lxml-objectify
and then do something like this:
>>> et = etree.parse(myfilename, parser)
You might also want to read the doc page on parsing:
http://codespeak.net/lxml/dev/parsing.html
> First I need to get first child (This
> is where I am stuck.)
>>> root.DVD
> and assign it to the python model.
???
> Get second
> child and assign it to the python model, so on. I looked at the
> documentation, it's kind of hard to grasp for a newb.
Why don't you run a loop over them?
>>> for dvd in root.DVD:
... print dvd.get("id")
1
2
I have a slight intuition that it might also help you to read the Python
tutorial first.
Regards,
Stefan
More information about the lxml-dev
mailing list