-2

我正在尝试提取 xml 文件中序列下的名称元素。我在顶部粘贴了一个示例 xml 来说明。有了这个,我想通过指导从 01 Interview_been 中获得文本并将其写入文件。xml 中有多个序列标签,我试图弄清楚如何通过它并提取它。我试图弄清楚如何使用 xml.etree 和 xml.dom.minidom 但我似乎无法将我的大脑包裹在它周围。我能够从序列标签中获取所有 id 值,但不能从名称元素中获取。我在xml之前粘贴我的代码。

from xml.etree import ElementTree


file = open("xmldump.txt", "r")
filedata = file.read()
file.close()

with open('test.xml', 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.iter('name'):
    sequenceid = node.attrib.get('name')
    print '  %s' % (sequenceid)
    newLine = sequenceid + "\n"
    file = open("xmldump.txt", "w")
    file.write(newLine)
    file.close()

这是 XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xmeml>
<xmeml version="5">
<bin>
<uuid>0F5D72FA-54E4-4DE8-81D7-CC33F5C43836</uuid>
<updatebehavior>add</updatebehavior>
<name>Logged</name>
<children>
    <sequence id="01 Interview_been successful through mentorship">
        <uuid>12FB944D-83EA-4527-9A54-2130A42E3A06</uuid>
        <updatebehavior>add</updatebehavior>
        <name>01 Interview_been successful through mentorship</name>
        <duration>1195</duration>
        <rate>
            <ntsc>TRUE</ntsc>
            <timebase>24</timebase>
        </rate>
        <timecode>
4

1 回答 1

5

好吧,我不确定您是否想要“id”属性或名称标签(您的代码令人困惑,它试图从“sequence”标签中提取“name”属性,但该标签只有一个“id “ 属性)。下面是提取两者的代码,应该可以帮助您开始了解 ElementTree 的工作原理

from xml.etree import ElementTree

with open('test.xml', 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.iter('sequence'):
    sequenceid = node.attrib.get('id')
    name = node.findtext('name')
于 2013-02-27T00:08:44.647 回答