[英]python xml - why find(“..”) doesn't return root
為什么當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>
Python的xml.etree.ElementTree
實現不記錄Element
的父級。 因此, XPath的文檔包括以下內容:
..
選擇父元素。 如果路徑嘗試到達start元素的祖先(調用元素find),則返回None
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.