簡體   English   中英

將xml轉換為json結構后,增加json中節點的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM