Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way or any framework in python to create an object model from a xml?

for example my xml file contains :

<layout name="layout1">
    <grid>
        <row>
            <cell colSpan="1" name="cell1"/>
        </row>
        <row>
            <cell name="cell2" flow="horizontal"/>
        </row>
    </grid>
</layout>

and I want to retrieve an object from the xml for example returned object structure be like this

class layout(object):
     def __init__(self):
         self.grid=None
class grid(object):
     def __init__(self):
         self.rows=[]
class row(object):
     def __init__(self):
         self.cels=[]
like image 282
Pooya Avatar asked Jul 04 '12 08:07

Pooya


People also ask

How do you process XML in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().

How do I flatten XML in Python?

By using xmltodict to transform your XML file to a dictionary, in combination with this answer to flatten a dict , this should be possible. Show activity on this post. well this is a very nice solution but it's not working with the below XML string <? xml version="1.0" encoding="utf-8"?>

How do I read an XML string in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.

How do I write data into an XML file using Python?

Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.


1 Answers

I've found my answer I used objectify in lxml package

this is a sample code:

from lxml import objectify

root = objectify.fromstring("""
 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <a attr1="foo" attr2="bar">1</a>
   <a>1.2</a>
   <b>1</b>
   <b>true</b>
   <c>what?</c>
   <d xsi:nil="true"/>
 </root>
""")

print objectify.dump(root)

it prints:

root = None [ObjectifiedElement]
    a = 1 [IntElement]
      * attr1 = 'foo'
      * attr2 = 'bar'
    a = 1.2 [FloatElement]
    b = 1 [IntElement]
    b = True [BoolElement]
    c = 'what?' [StringElement]
    d = None [NoneElement]
      * xsi:nil = 'true'
like image 191
Pooya Avatar answered Sep 19 '22 14:09

Pooya