簡體   English   中英

xml.etree - 將元素作為子元素插入特定元素

[英]xml.etree - insert element as a child at specific element

我有一個文件,其中包含一些 .txt 格式的原始數據,我需要將數據輸入到更結構化的 .xml 文檔中。 在 Python 中。 我的源文件大約有 10000 行,但為了使事情更容易,我只附加了一個包含三個短列表(“ID”、“名稱”和“父 ID”)的代碼。

original.txt 如下所示:

Ac  Value 1
Ac_05   Value 2 Ac
Ac_05_00    Value 3 Ac_05
Ac_15   Value 4 Ac_05

如果元素有一個父 ID(在我的代碼中稱為 pID 的列表),那么它應該是一個元素的子元素,該元素的 ID 與子元素的父 ID 相同......希望它有意義。

我已經得到了以下代碼:

import xml.etree.cElementTree as ET

IDs = ['Ac', 'Ac_05', 'Ac_05_00', 'Ac_15']
Names = ['Value 1', 'Value 2', 'Value 3', 'Value 4']
pID = ['', 'Ac', 'Ac_05', 'Ac']

# make xml file
Items = ET.Element('Items')

for i in range(len(IDs)):

    if pID[i] in IDs:

        # index of the parent ID
        # IDs.index(pID[i])

        # value of the parent ID
        # IDs[IDs.index(pID[i])]
       
        Item = ET.SubElement(Children, 'Item')

        ID = ET.SubElement(Item, 'ID')
        ID.text = IDs[i]

        Name = ET.SubElement(Item, 'Name')
        Name.text = Names[i]

        Children = ET.SubElement(Item, 'Children')

    else:
        Item = ET.SubElement(Items, 'Item')
            
        ID = ET.SubElement(Item, 'ID')
        ID.text = IDs[i]

        Name = ET.SubElement(Item, 'Name')
        Name.text = Names[i]

        Children = ET.SubElement(Item, 'Children')

tree = ET.ElementTree(Items)
ET.indent(tree, space='\t', level=0)
tree.write('filename.xml', encoding='utf-8')

我無法弄清楚我如何將 append 子項添加到.xml 中的特定元素。 例如,ID 為“AC_15”的最后一項應該是“AC”的子項。 正確的 output in.xml 應該如下所示:

<Items>
    <Item>
        <ID>Ac</ID>
        <Name>Value 1</Name>
        <Children>
            <Item>
                <ID>Ac_05</ID>
                <Name>Value 2</Name>
                <Children>
                    <Item>
                        <ID>Ac_05_00</ID>
                        <Name>Value 3</Name>
                        <Children/>                         
                    </Item>
                </Children>
            </Item>
            <Item>
                <ID>Ac_15</ID>
                <Name>Value 4</Name>
                <Children/>
            </Item>
        </Children>
    </Item>
</Items>

有沒有人像我一樣對 Python 的初學者有什么建議?

盡管對 if 部分的更改很小,但您還有一個很大的變化,因此您應該專注於真正的差異。 這里真正的區別只是項目的父元素

我做了一個字典來存儲所有父元素的子標簽,應該沒問題。 至少它可以按預期適用於您的示例

Items = ET.Element('Items')
elems=dict()
for id_, name, pid in zip(IDs, Names, pID):
    el=ET.Element('Item')
    ET.SubElement(el, 'ID').text = id_
    ET.SubElement(el, 'Name').text = name
    elems[id_]=ET.SubElement(el, 'Children')
    
    if not pid:
        parent=Items
    else:
        parent=elems[pid]
    parent.append(el)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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