ElementTree元素索引查找

15 投票
3 回答
19135 浏览
提问于 2025-04-16 04:25

我正在使用 xml.etree.ElementTree 这个模块,用 Python 3.1 从另一个结构化文档创建一个 XML 文档。

请问我可以用哪个 ElementTree 的函数来获取一个已经存在的子元素的索引呢?

3 个回答

-1
def alarms_validation(self, path, alarm_no, alarm_text):
    with open(path) as f:
        tree = et.parse(f)
        root = tree.getroot()
        try:
            for x in xrange(10000):
                print x
                for y in xrange(6):
                    print y
                    if root[x][y].text == alarm_no:
                        print "found"
                        if root[x][y+1].text != alarm_text:
                            print "Alarm text is not proper"
                        else:
                            print "Alarm Text is proper"
        except IndexError:
            pass

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

0
import xml.etree.ElementTree as ET
root=ET.Element('C:\Users\Administrator\Desktop\ValidationToolKit_15.9\ValidationToolKit_15.9\NE3S_VTK\webservice\history\ofas.2017-1-3.10-55-21-608.xml')
childnew=ET.SubElement(root,"354")
root.getchildren().index(childnew)
0
list(root).index(childnew)
0

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

13

getchildren 方法会返回一个元素对象的子元素列表。你可以接着使用列表自带的索引方法。

>>> import xml.etree.ElementTree as ET
>>> root = ET.Element("html")
>>> head = ET.SubElement(root, "head")
>>> body = ET.SubElement(root, "body")
>>> root.getchildren().index(body)
1

撰写回答