Saving a Specific value from XML in Python with identical column names

So I've imported an XML file into Python and have saved most of what I want in a new dataframe. However, my problem is I've noticed there are variables with the same name and so when I call that particular variable by name, there are multiple values that appear for the same name and it is saving the first value it recognizes. I want to be able to save a specific value from among the multiple values. Is this possible even with all of them having the same name? The XML file is not something I can edit as it's imported from a central database.

Here is my code:

tree = ET.ElementTree(ET.fromstring(str(xml_file)))
root = tree.getroot()

import pandas as pd
tags = {"tags":[]}

for varaible1 in root.iter('varaible1'):
    tag = {}
    varaible1= varaible1.text
    tag["varaible1"] = varaible1

for varaible2 in root.iter('varaible2'):
    varaible2= varaible2.text
    tag["varaible2"] = varaible2

for varaible3 in root.iter('varaible3 '):
    varaible3 = varaible3 .text
    tag["varaible3 "] = varaible3 

tags["tags"].append(tag)

dataframe = pd.DataFrame(tags["tags"])

This is what the XML file looks like:

<response error_code="0">
  <xml_root>
    <report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <report_data>
        <variable1>2021-06-01</variable1>
        <variable2>1</variable2>
        <variable3>0</variable3>
        <variable3>5</variable3>
        <variable3>10</variable3>

I want the dataframe I create to look like this:

    variable1     variable2     variable3
   2021-06-01             1             5

And what I'm getting is this:

    variable1     variable2     variable3
   2021-06-01             1             0

As it's calling the first occurrence of variable3. I want to be more specific with which value I grab, for example, the second occurrence of variable3.



Read more here: https://stackoverflow.com/questions/67940923/saving-a-specific-value-from-xml-in-python-with-identical-column-names

Content Attribution

This content was originally published by Kardinol at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: