views:

58

answers:

1

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 ):

  1. Display a list of all books with their respective attributes
  2. Enable viewing of further details of a book by selecting it from the list
A: 

Firstly, "list" isn't a very good variable because it "shadows" the built-in type "list."

Now, say you have this xml:

<root>
<node1 val="foo">derp</node1>
<node2 val="bar" />
</root>

Now, you could do this:

root = objectify.parse("myfile.xml")
print root.node1.get("val") # prints "foo"
print root.node1.text # prints "derp"
print root.node2.get("val") # prints "bar"

Another tip: when you have lots of nodes with the same name, you can loop over them.

>>> xml = """<root>
    <node val="foo">derp</node>
    <node val="bar" />
    </root>"""
>>> root = objectify.fromstring(xml)
>>> for node in root.node:
    print node.get("val")

foo
bar

Edit

You should be able to simply set your django context to the books object, and use that from your templates.

context = dict(books = root.book,
               # other stuff
               )

And then you'll be able to iterate through the books in the template, and access each book object's attributes.

Ryan Ginstrom
Thanx for the tip on list...I'll give this a try and see...probably have to adapt a bit since I have a large file to parse
Stephen
If you could describe the kind of XML file you have in a little more detail, and what you want to do, I might be able to offer some more tips for dealing with it.
Ryan Ginstrom
@Ryan, see my edit above...I hope this helps you get an idea of what I'm attempting
Stephen