python xml parses example details
- 2020-05-17 05:44:22
- OfStack
python xml parsing
first.xml
<info>
<person >
<id>1</id>
<name>fsy</name>
<age >24</age>
</person>
<person>
<id>2</id>
<name>jianjian</name>
<age>24</age>
</person>
<count id ='1'>1000</count>
</info>
from xml.etree import ElementTree as etree
Read in
def read_xml(file):
# parse() The function will return 1 Objects that represent the entire document. This is not the root element. To get a reference to the root element, call getroot() Methods.
tree = etree.parse(file)
root = tree.getroot()
return root
Get the information
def print_node(node):
''''' Print node basic 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")
[<Element 'person' at 0x00000000033388B8>, <Element 'person' at 0x0000000003413D68>]
Note: findall Only direct child nodes are queried
>>> r1 = root.findall("id")
>>> r1
[]
>>> r =tree.findall(".//id")
>>> for e in r:
print( e,e.text)
<Element 'id' at 0x00000000034279F8> 1
<Element 'id' at 0x0000000003427B38> 2
find:
#find() Method to return the first 1 The elements that match. When we thought there would only be 1 We have 1 match, or we have multiple matches but we only care about the first 1 This method is very useful in the future.
>>> res[0].find("id")
<Element 'id' at 0x0000000003413CC8>
>>> print_node(res[0].find("id"))
node.tag:id
node.attrib:{}
node.text:1
find search failed:
When using find, note that in a Boolean context, if the ElementTree element object does not contain child elements, its value is considered to be False (that is, if len (element) is equal to 0). This means that if element ('... ') is not testing whether the find() method found a match; This statement tests whether the matched element contains child elements. To test whether the find() method returns an element, if element.find ('... ') is not None.
>>> bk = res[0].find("no")
>>> bk
>>> type(bk)
<class 'NoneType'>
>>> res[0].find("id")
<Element 'id' at 0x0000000003413CC8>
>>> 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
Thank you for reading, I hope to help you, thank you for your support of this site!