पायथन एक्सएमएल डेटा को एक्सपैट नामक अपने इनबिल्ट मॉड्यूल के माध्यम से पढ़ने और संसाधित करने की अनुमति देता है। यह एक गैर-मान्य एक्सएमएल पार्सर है। यह एक XML पार्सर ऑब्जेक्ट बनाता है और इसके ऑब्जेक्ट की विशेषताओं को विभिन्न हैंडलर फ़ंक्शंस में कैप्चर करता है। नीचे दिए गए उदाहरण में हम देखेंगे कि कैसे विभिन्न हैंडलर फ़ंक्शन हमें XML फ़ाइल को पढ़ने के साथ-साथ आउटपुट डेटा के रूप में विशेषता मान देने में मदद कर सकते हैं। इस उत्पन्न डेटा का उपयोग प्रसंस्करण के लिए किया जा सकता है।
उदाहरण
import xml.parsers.expat
# Capture the first element
def first_element(tag, attrs):
print ('first element:', tag, attrs)
# Capture the last element
def last_element(tag):
print ('last element:', tag)
# Capture the character Data
def character_value(value):
print ('Character value:', repr(value))
parser_expat = xml.parsers.expat.ParserCreate()
parser_expat.StartElementHandler = first_element
parser_expat.EndElementHandler = last_element
parser_expat.CharacterDataHandler = character_value
parser_expat.Parse(""" <?xml version="1.0"?>
<parent student_rollno="15">
<child1 Student_name="Krishna"> Strive for progress, not perfection</child1>
<child2 student_name="vamsi"> There are no shortcuts to any place worth going</child2>
</parent>""", 1) आउटपुट
उपरोक्त कोड को चलाने से हमें निम्नलिखित परिणाम मिलते हैं -
first element: parent {'student_rollno': '15'}
Character value: '\n'
first element: child1 {'Student_name': 'Krishna'}
Character value: 'Strive for progress, not perfection'
last element: child1
Character value: '\n'
first element: child2 {'student_name': 'vamsi'}
Character value: ' There are no shortcuts to any place worth going'
last element: child2
Character value: '\n'
last element: parent