I’m trying to use the lxml library to parse an XML file…what I want is to use XML as the datasource, but still maintain the normal Django-way of interactive with the resulting objects…from the docs, I can see that lxml.objectify is what I’m suppossed to use, but I don’t know how to proceed after: list = objectify.parse('myfile.xml')
Any help will be very much appreciated. Thanks.
A sample of the file (has about 100+ records) is this:
<store>
<book>
<publisher>Hodder &...</publisher>
<isbn>345123890</isbn>
<author>King</author>
<comments>
<comment rank='1'>Interesting</comment>
<comments>
<pages>200</pages>
</book>
<book>
<publisher>Penguin Books</publisher>
<isbn>9011238XX</isbn>
<author>Armstrong</author>
<comments />
<pages>150</pages>
</book>
</store>
From this, I want to do the following (something just as easy to write as Books.objects.all() and Books.object.get_object_or_404(isbn=selected) is most preferred ):
- Display a list of all books with their respective attributes
- Enable viewing of further details of a book by selecting it from the list
Firstly, “list” isn’t a very good variable because it “shadows” the built-in type “
list.”Now, say you have this xml:
Now, you could do this:
Another tip: when you have lots of nodes with the same name, you can loop over them.
Edit
You should be able to simply set your django context to the books object, and use that from your templates.
And then you’ll be able to iterate through the books in the template, and access each book object’s attributes.