This article mainly introduces detailed information about pythonxml parsing instances. here we will illustrate how to implement it. if you need it, you can refer to python xml parsing.
First. xml
1
fsy
24
2
jianjian
24
1000
From xml. etree import ElementTree as etree
Read
Def read_xml (file): # The parse () function returns an object that represents the entire document. This is not the root element. To obtain references to the root element, call the getroot () method. Tree = etree. parse (file) root = tree. getroot () return root
Get information
Def print_node (node): ''' print basic node information ''' print ("node. tag: % s "% node. tag) print ("node. attrib: % s "% node. attrib) print ("node. text: % s "% node. text)
Search:
Find_all >>> root = read_xml ('First. XML') >>> res = root. findall ("person ")[
,
] Note: findall only queries direct subnodes> r1 = root. findall ("id") >>> r1 [] >>> r = tree. findall (". // id ") >>> for e in r: print (e, e. text)
1
2
Find:
# The find () method is used to return the first matched element. This method is useful when we think there will be only one match or multiple matches but we only care about the first one. >>> Res [0]. find ("id ")
>>> Print_node (res [0]. find ("id") node. tag: id node. attrib: {} node. text: 1
Find failed:
When using find, note that in a Boolean context, if the ElementTree element object does not contain child elements, its value is considered False (that is, if len (element) is equal to 0 ). This means that if element. find ('... ') is not used to test whether a matching item is found in the find () method; this statement is used to test whether the matched element contains a child element. To test whether the find () method returns an element, use if element. find ('...') is not None.
>>> bk = res[0].find("no") >>> bk >>> type(bk)
>>> res[0].find("id")
>>> if res[0].find("id"): print("find") else: print("not find") not find >>> if res[0].find("id") is not None: print("find") else: print("not find") find
The above is a detailed explanation of the python xml parsing instance. thank you for reading it. I hope to help you. For more articles, please refer to the PHP Chinese website (www.php1.cn )!