从层次结构级别和文本创建XML树

时间:2019-01-06 15:54:37

标签: python xml python-3.x

我有一个文本文件,其中包含层次结构级别和类似这样的文本:

1 A
2 B
2 C
3 D
3 E
2 F
1 G   

我想创建一个像这样的XML文档:

<A>
  <B></B>
  <C>
    <D></D>
    <E></E>
  </C>
  <F></F>
</A>
<G></G>

是否有执行此工作的python库?

1 个答案:

答案 0 :(得分:0)

与此同时,我自己找到了答案。

import xml.etree.ElementTree as ET

class item:
""" class to hold level and tag """
    def __init__(self, line):
        __s_list = (line.split(' ', 1))
        if len(__s_list) != 2:
            raise Exception("Invalid list length: " + str(len(__s_list)) + " at " + line)
        self.level = int(__s_list[0])
        self.tag = __s_list[1].lstrip()

# Read infile and put items into list
list = []
with open(path + "sample.txt") as infile:
    for line in infile:
        line = line.rstrip('\n')
        list.append(item(line))

root = ET.Element("root")
tree = ET.ElementTree(root)

# Create list to hold last parent per level
last_parents = []
last_parents[0] = root

for element in list:
    # extend last_parents if necessary
    if len(last_parents) <= element.level + 1:
    last_parents.append[None]
    # insert element into tree and save it in last_parents
    last_parents[element.level] =  ET.SubElement(last_parents[element.level-1], element.tag)
    print(str(element.level) + ": "+ element.tag)

tree.write(path+"sample.xml")

礼物:

<root>
    <A>
        <B />
        <C>
            <D />
            <E />
        </C>
        <F />
    </A>
    <G  />
</root>