Parse XML in Python

Source: Internet
Author: User

Python has three methods to parse XML, sax, Dom, and elementtree.
### 1.sax (Simple API for XML)
The standard pyhton library contains a SAX Parser. Sax is a typical extremely fast tool that does not occupy a large amount of memory when parsing XML.
But this is based on the callback mechanism, so in some data, it will call some methods for transmission. This means that you must specify a handle for the data,
It is very difficult to maintain your own status.

### 2.dom( Document Object Model)
Compared with sax, the typical disadvantage of Dom is that it is slow and consumes more memory, because Dom reads the entire XML number into the memory and
The first node in creates an object. The advantage of using Dom is that you do not need to track the status, because every node knows who it is.
Parent node, who is a child node. However, Dom is a little difficult to use.

### 3. elementtree (element tree)
Elementtree is like a lightweight Dom with convenient and friendly APIs.CodeHigh Availability, fast speed, and low memory consumption.
This section describes elementtree.


The following is a reprinted example:

Test. XML is as follows:

 

[HTML] View plaincopy

  1. <Span Style="Font-size: 13px ;"><?XML Version="1.0" Encoding="UTF-8"?>
  2. <Root>
  3.  <Person Age="18">
  4. <Name>Hzj</Name>
  5. <Sex>Man</Sex>
  6.  </Person>
  7.  <Person Age="19" Des="Hello">
  8. <Name>Kiki</Name>
  9. <Sex>Female</Sex>
  10.  </Person>
  11. </Root></Span>

 

1. load XML files

There are two ways to load an XML file: loading a specified string and loading a specified file.

2. Obtain the Element Method

A) through getiterator

B) getchildren

C) Find Method

D) findall Method

[Python] View plaincopy

  1. <Span style ="Font-size: 13px ;">#-*-Coding: UTF-8 -*-
  2. FromXML. etreeImportElementtree
  3. DefPrint_node (node ):
  4. '''''Print basic node information '''
  5. Print "============================================== ======="
  6. Print "Node. attrib: % s"% Node. attrib
  7. IfNode. attrib. has_key ("Age")>0:
  8. Print "Node. attrib ['age']: % s"% Node. attrib ['Age']
  9. Print "Node. Tag: % s"% Node. Tag
  10. Print "Node. Text: % s"% Node. Text
  11. DefRead_xml (text ):
  12. '''''Read XML file '''
  13. # Loading XML files (two methods: loading a specified string and loading a specified file)
  14. # Root = elementtree. parse (R "D:/test. xml ")
  15. Root = elementtree. fromstring (text)
  16. # Obtain the Element Method
  17. #1 through getiterator
  18. Lst_node = root. getiterator ("Person")
  19. ForNodeInLst_node:
  20. Print_node (node)
  21. #2 Use getchildren
  22. Lst_node_child = lst_node [0]. Getchildren ()[0]
  23. Print_node (lst_node_child)
  24. #3. Find Method
  25. Node_find = root. Find ('Person')
  26. Print_node (node_find)
  27. #4. findall Method
  28. Node_findall = root. findall ("Person/name")[1]
  29. Print_node (node_findall)
  30. If_ Name _ ='_ Main __':
  31. Read_xml (open ("Test. xml"). Read ())
  32. </Span>


Think about why? Do not understand, please refer to the following

 

[Python] View plaincopy

  1. # Encoding = UTF-8
  2. FromXML. etreeImportElementtree as et
  3. # Identify the age of all people
  4. Per = ET. parse ('Test. xml')
  5. P = per. findall ('/Person')
  6. ForXInP:
  7. PrintX. attrib
  8. Print
  9. ForOneperInP:# Finding the person Node
  10. ForChildInOneper. getchildren ():# Find the child node of the person Node
  11. PrintChild. Tag,':', Child. Text
  12. Print 'Age :', Oneper. Get ('Age')
  13. Print '############'

The result is as follows:

[Python] View plaincopy

  1. {'Age':'18'}
  2. {'Age':'19','Des':'Hello'}
  3. Name: hzj
  4. Sex: Man
  5. Age:18
  6. ############
  7. Name: Kiki
  8. Sex: Female
  9. Age:19
  10. ############ 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.