[英]Increment the value of a node in the json after converting the xml to json structure
我有当前格式的xml。 我使用python中的xmltodict库将此xml转换为json。
<?xml version="1.0" encoding="UTF-8" ?>
<MyHouse>
<Garden>
<InfoList>
<status value = "0"/>
</InfoList>
<Flowers>
<InfoList>
<status value = "0"/>
</InfoList>
</Flowers>
</Garden>
</MyHouse>
在将json字典发送到xmltodict
方法后,我希望它看起来像这样。
json_tree =
{
"MyHouse": {
"Tid": "1", --> Need to add this node and its value increments from '1'.
"status": "0", --> This node is added to the root level node ONLY as it
is not in the xml shown above !!
"Garden": {
"Tid": "2", --> Incremeneted to 2
"InfoList": {
"status": {
"@value": "0"
}
},
"Flowers": {
"Tid": "3", ---> Incremented to 3
"InfoList": {
"status": {
"@value": "0"
}
}
}
}
}
}
正如我们在上面的json结构中看到的那样,我希望能够向根节点(在本例中为“ MyHouse”)添加默认的“状态”:“ 0”。
我还希望能够为每个节点(例如“花园”,“花朵”)添加“ Tid”。请注意,xml中可能还有更多级别,但为简单起见,此处未显示。具有通用方法。
我当前的实现如下。
def add_status(root, el_to_insert):
# Add "id":"#" to the nodes of the xml
for el in root:
if len(list(el)): # check if element has child nodes
el.insert(1, el_to_insert)
el_to_insert = el_to_insert.text + 1 ---> This line of code doesn't seem to work. I want to increment the value of "Tid" everytime its added to the tree?
add_status(el, el_to_insert)
def ConverxmltoJson(target):
xmlConfigFile = ET.parse(target)
root = xmlConfigFile.getroot()
state_el = ET.Element("Tid") # Create `Tid` node, not sure how to add the "status" node to the root "Garden" node.
state_el.text = "0"
root.insert(1, state_el)
add_status(root, state_el)
json_str = xmltodict.parse(ET.tostring(root, encoding="utf8"))
with open("xmlconfig.xml") as xmlConfigFile:
ConverxmltoJson(xmlConfigFile)
如果有人可以帮助我解决问题,我将非常高兴。
谢谢。
通过以下更改,我能够解决根节点的“状态”和“ Tid”的部分。
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)
我现在有一个新问题,并在链接上打开了一个新问题: 将“ Tid”节点值更新为全局变量的最终值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.