问题
This is the xml config file. The xmltojson converts this xml to a json string at the end after adding the "status" node to the root and the "Tid" recursively to each root node in the xml.
<?xml version="1.0" encoding="UTF-8" ?>
<MyHouse>
<Garden>
<InfoList>
<status value = "0"/>
</InfoList>
<Flowers>
<InfoList>
<status value = "0"/>
</InfoList>
</Flowers>
</Garden>
</MyHouse>
# Global Variable
idValue = 0
def xmltojson(target):
xmlConfigFile = ET.parse(target)
root = xmlConfigFile.getroot()
state_el = ET.Element("state") # Create `state` node for root node
state_el.text = "0"
root.insert(1, state_el)
# Adding the Tid node to root level
id_node = ET.Element("Tid") # Create `Tid` node
id_node.text = "0"
root.insert(1, id_node)
# Add 'Tid' with increasing values based on the global variable "tid_value" to each node in the xml
add_Tid(root, id_node)
json_str = xmltodict.parse(ET.tostring(root, encoding="utf8"))
print(json.dump(result))
def add_Tid(root, el_to_insert):
# Add "id":"#" to the nodes of the xml
for el in root:
if len(list(el)) and el.attrib: # check if element has child nodes
el.insert(1, el_to_insert)
global idValue # I think the error is in here
idValue += 1
el_to_insert.text = str(idValue)
add_status(el, el_to_insert)
The json output I get is as the following.
json_tree =
{
"MyHouse": {
"Tid": "3", # Should be "1" instead of "3"
"status": "0",
"Garden": {
"Tid": "3", # Should be "2" instead of "3"
"InfoList": {
"status": {
"@value": "0"
}
},
"Flowers": {
"Tid": "3", # Correct value of "3"
"InfoList": {
"status": {
"@value": "0"
}
}
}
}
}
}
Problem/Issue I have to resolve:
I am not able to understand why all the "Tid": "3" are 3 rather than being "1" for the "MyHouse", "2" for the "Garden", and "3" for the "Flowers".
I am assigning the global variable idValue and assign it individually to each node. I cant understand what the issue is in the add_Tid method.
来源:https://stackoverflow.com/questions/57433580/updating-the-tid-node-value-updates-to-the-final-value-of-the-global-variable