Python Parse XML file _python

Source: Internet
Author: User
Python files:
Copy Code code as follows:

#parsexml. py
#本例子参考自python联机文档, made the appropriate alterations and additions

Import Xml.parsers.expat

#控制打印缩进
Level = 0

#获取某节点名称及属性值集合
def start_element (name, attrs):
Global level
print ' *level, ' Start element: ', name, attrs
Level = level + 1

#获取某节点结束名称
def end_element (name):
Global level
Level = Level-1
print ' *level, ' end element: ', name

#获取某节点中间的值
def char_data (data):
if (data = = ' \ n '):
Return
if (Data.isspace ()):
Return
Global level
print ' *level, ' Character data: ', data

p = xml.parsers.expat.ParserCreate ()

P.startelementhandler = Start_element
P.endelementhandler = End_element
P.characterdatahandler = Char_data
P.returns_unicode = False

f = File (' sample.xml ')
P.parsefile (f)
F.close ()

XML file (sample.xml):
Copy Code code as follows:

<contacts id= "Bluecrystal" >
<item name= "Keen" fff= "ddd" >
<telephone type= "Phone" >222222222</telephone>
<telephone type= "mobile" >134567890</telephone>
</item>
<item name= "BCM" >
<telephone type= "Phone" >11111111</telephone>
<telephone type= "mobile" >15909878909</telephone>
</item>
</contacts>

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.