Convert XML to python objects using lxml

I'm trying to use the lxml library to parse an XML file ... I want to use XML as a data source, but at the same time support the normal Django-way of interacting with the resulting objects ... from docs, I see that lxml.objectify is something that I intend to use, but I do not know how to proceed after:list = objectify.parse('myfile.xml')

Any help would be greatly appreciated. Thank.

Sample file (has about 100 entries):

<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 next (something 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 matching attributes
  • Enable viewing additional information about the book by selecting it from the list
+3
1

-, "" , "" "list".

, , xml:

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

:

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"

: , .

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

django books .

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

.

+1

Source: https://habr.com/ru/post/1753148/


All Articles