pythonxml为什么find(“..”)不返回

2024-06-12 22:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

root.findall("*")返回element时,element.find("..")为什么不返回root?你知道吗

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

XML文件的前5行

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

Tags: nodetreeiftagsrootxmlelementfind
1条回答
网友
1楼 · 发布于 2024-06-12 22:41:19

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

.. Selects the parent element. Returns None if the path attempts to reach the ancestors of the start element (the element find was called on).

相关问题 更多 >