How to append data to a parsed XML object - Python

110 views Asked by At

I am trying to take an xml document parsed with lxml objectify in python and add subelements to it.

The problem is that I can't work out how to do this. The only real option I've found is a complete reconstruction of the data with objectify.Element and objectify.SubElement, but that... doesn't make any sense.

With JSON for instance, I can just import the data as an object and navigate to any section and read, add and edit data super easily.

How do I parse an xml document with objectify so that I can add subelement data to it?

data.xml

<?xml version='1.0' encoding='UTF-8'?>
<data>
  <items>
    <item> text_1 </item>
    <item> text_2 </item>
  </items>
</data>

I'm sure there is an answer on how to do this online but my search terminology is either bad or im dumb, but I can't find a solution to this question. I'm sorry if this is a duplicate question.

1

There are 1 answers

0
Gunty On BEST ANSWER

I guess it has been quite difficult explain the question, but the problem can essentially be defined by an ambiguity with how .Element and .SubElement can be applied.

This reference contains actionable and replicable ways in which one can append or add data to a parsed XML file.

Solving the key problem of:

How do I reference content in a nested tag without reconstructing the entire tree?

The author uses the find feature, which is called with root.findall(./tag)

This allows one to find the nested tag that they wanted without having to reconstruct the tree.


Here is one of the examples that they have used:

cost = ["$2000","$3000","$4000")
traveltime = ["3hrs", "8hrs", "15hrs"]
i = 0

for elm in root.findall("./country"):
    ET.SubElement(elm, "Holiday", attrib={"fight_cost": cost[i],
                                          "trip_duration": traveltime[i]})
    i += 1

This example also answers the question of How do you dynamically add data to XML?

They have accomplished this by using a list outside of the loop and ieteration through it with i

In essence, this example helps explain how to reference nested content without remaking the entire tree, as well as how to dynamically add data to xml trees.