python xml - 为什么find(" ..")没有返回root

时间:2016-06-29 18:31:05

标签: python xml

element.find("..")返回root时,为什么不root.findall("*")返回element

def XML_Extract_Node_Tags(Tree, Node_Tags):
    """
    :param Tree: xml.etree.ElementTree
    :param Node_Tags: list
    :return: ReturnVal:
    """

    for el in Tree.findall("//"):
        if el.tag not in Node_Tags:
            print(el.tag)
            # Need to remove the element and set its children equal to parent
            for subel in el.findall("*"):
                ## Add subel to grandparent (if exists)
                grand_parent = subel.find('../..')
                if grand_parent:
                    # If it has a grand parent
                    grand_parent.append(subel)
            # Remove el from tree
            if not el.find(".."):
                print(el.tag, el.attrib)
            else:
                el.find("..").remove(el)

    ReturnVal = Tree
    return ReturnVal

前5行XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE build SYSTEM "build.dtd">
<build id="58" localAgents="true" cm="usl000348:80" start="6/1/2016 3:31:19 PM">
<properties>
<property name="CommandLine">emake all --emake-annodetail=waiting,registry,md5,lookup,history,file,env --emake-annofile=../Emake-2agents-1st.xml --emake-root=../</property>

1 个答案:

答案 0 :(得分:2)

Python的xml.etree.ElementTree实现不会记录Element的父级。因此,the documentation for XPath包括:

  

..选择父元素。如果路径尝试到达start元素的祖先(调用元素find),则返回None