Python 将xml转换为json结构后,增加json中节点的值

Python 将xml转换为json结构后,增加json中节点的值,python,json,xml,xmltodict,Python,Json,Xml,Xmltodict,我有一个当前格式的xml。我使用python中的xmltodict库将此xml转换为json <?xml version="1.0" encoding="UTF-8" ?> <MyHouse> <Garden> <InfoList> <status value = "0"/> </InfoList&g

我有一个当前格式的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结构中所看到的,我希望能够向根节点添加一个默认的“状态”:“0”,在本例中是“MyHouse”

我还希望能够为每个节点添加“Tid”,例如“Garden”、“Flowers”。注意,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)

我现在有一个新问题,并在link上提出了一个新问题:

我只想将XML或JSON反序列化为一个模型,将reserialize反序列化为JSON@Ajax1234你能帮我吗?
    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)