更新“ Tid”节点值将更新为全局变量的最终值

时间:2019-08-09 15:56:24

标签: python json xml xml-parsing

这是xml配置文件。在将“状态”节点添加到根目录并将“ Tid”递归添加到xml中的每个根节点后,xmltojson将此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>
# 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)

我得到的json输出如下。


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:

我不明白为什么所有“ Tid”:“ 3”都是3,而不是“ MyHouse”是“ 1”,“ Garden”是“ 2”,“ Flowers”是“ 3” “。

我正在分配全局变量idValue并将其分别分配给每个节点。我无法理解add_Tid方法中的问题所在。

0 个答案:

没有答案