0

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.

mzjn
  • 48,958
  • 13
  • 128
  • 248
Gunty
  • 1,841
  • 1
  • 15
  • 27
  • Unclear. What exactly have you tried? What is it that doesn't make sense? – mzjn May 31 '21 at 08:26
  • To distill it into a single line: how do I parse an xml document and **add** stuff to it. Sorry about it very simple but I can't find an answer to it. – Gunty May 31 '21 at 08:36
  • Specifically, what `function` i can use to actually add to it. My understanding is that functions like `objectify.Element` and `objectify.SubElement` can only be used to `construct` xml datasets and not `append` to existing datasets. Like, I literally dont understand how you can append data to a parsed dataset. Does that sort of make sense? – Gunty May 31 '21 at 08:44

1 Answers1

0

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.

Gunty
  • 1,841
  • 1
  • 15
  • 27