Just a heads up, I’m using lxml imported like this: from lxml import etree.
I’m trying to make some working code more flexible. My script takes an input .xml file containing all the items in an order by name, refers to a dictionary containing item ID numbers and item names to generate a list of item IDs based off that .xml file, and then polls a web server for the price data of those item IDs which it then uses to output a grand total cost. My question is not about any of these steps.
Rather my question is about how to handle parsing an .xml file that contains more than one order in it.
So far my sample .xml file might look like this:
<?xml version="1.0" ?>
<cars>
<order="This is a test order">
<description value=""/>
<carType value="Model1"/>
<upgrade slot="interior 0" type="Leather Seats"/>
<upgrade slot="interior 1" type="6-Disc CD Player"/>
</order>
</cars>
I can parse this into a list that includes both the base item carType (which is the model of car) and the various upgrades like this:
for element in root.iterchildren('carType'):
modlist.append ("%s" % (element.get('value')))
for element in root.iter('upgrade'):
modlist.append ("%s" % str.upper((element.get('type'))))
and it would give me a list called modlist like ['Model1', 'Leather Seats', '6-Disc CD Player'] which I can run through my other functions to get the ID numbers for those items and from there get the price information and total it up to find out how much this Model1 car with a Leather Seat upgrade and a 6-Disc CD Player upgrade would cost.
Here is where I run in to difficulty. How can I have multiple cars in one .xml file? An example might look like this:
<?xml version="1.0" ?>
<cars>
<order="This is a test order">
<description value=""/>
<carType value="Model1"/>
<upgrade slot="interior 0" type="Leather Seats"/>
<upgrade slot="interior 1" type="6-Disc CD Player"/>
</order>
<order="This is a 2nd order">
<description value=""/>
<carType value="Model3"/>
<upgrade slot="interior 0" type="Vinyl Seats"/>
<upgrade slot="wheels 0" type="Chrome Wheels"/>
<upgrade slot="wheels 1" type="8 Ply Tires"/>
</order>
<order="This is a 3rd order">
<description value=""/>
<carType value="Model7"/>
<upgrade slot="engine 0" type="V8"/>
<upgrade slot="interior 0" type="Leather Seats"/>
<upgrade slot="interior 1" type="Sunroof"/>
</order>
</cars>
I want to run my functions on one order at a time so that this example would output 3 numbers – the grand total price of this Model1 car with its upgrades, the grand total price of the Model3 car with its upgrades, and the grand total price of the Model7 car with its upgrades.
How can I tell my functions to just run on one order at a time? I’m thinking something about iterchild() but I can’t get anything to work.
Instead of calling
root.iterchildren, useorder.iterchildren, whereorderiterates through<order>elements: