2

我有一个当前格式的 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 dict 在我将它发送到方法后看起来像这样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 结构中看到的那样,我希望能够将默认的“status”:“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) 

如果有人可以帮助我解决问题,我会很高兴。

谢谢你。

4

1 回答 1

0

通过以下更改,我能够解决我必须将“状态”到根节点和“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”节点值更新为全局变量的最终值

于 2019-08-09T15:56:36.663 回答