【问题标题】:ElementTree element index look upElementTree 元素索引查找
【发布时间】:2010-09-21 17:54:44
【问题描述】:

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

我可以使用什么ElementTree 函数来返回现有子元素的索引?

【问题讨论】:

    标签: python elementtree


    【解决方案1】:

    getchildren 方法返回一个 Element 对象的子元素列表。然后,您可以使用列表的内置索引方法。

    >>> 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
    

    【讨论】:

    • 谢谢,正是我想要的。
    • 提醒一下 - list(root).index(body) 现在是执行此操作的正确方法。 getchildren() 已被弃用
    【解决方案2】:
    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
    

    【讨论】:

    • 您可能想为此添加几句解释,即“先用getchildren()创建一个列表,然后用index()获取它的索引”
    【解决方案3】:
    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
    

    【讨论】:

    • 这符合我的要求。我得到了索引,一个得到了索引,我是验证字符串。以上发布的内容对我不起作用。
    • 如何回答这个问题?这似乎完全无关。
    • @mzjn 这里 Print x 和 Print y 是元素树的索引。另一种查找索引的方法。
    • 没有人可以按原样获取您的代码并测试运行它。它并不完整。完全不清楚它是如何回答这个问题的。 “Alarms_Validation”与所询问的内容到底有什么关系?
    • @mzjn 您是绝对正确的,没有人可以按原样使用此代码,但可以采用另一种方法来查找子元素的索引。这里报警相关文字,请用户忽略。只需检查 X 和 Y 是否是索引。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2017-09-23
    • 2015-05-07
    • 2012-03-03
    相关资源
    最近更新 更多