XML अवलोकन
XML (Extensible Markup Language) संरचित डेटा के लिए मानक फॉर्मेट है। पायथन में दो मुख्य पार्सर हैं: ElementTree (सरल, पायथनिक) और DOM (विशिष्ट, ट्री-आधारित)।
नमूना XML (TutorialsList.xml)
<?xml version="1.0"?>
<Tutorials>
<Tutorial id="Tu101">
<author>Vicky, Matthew</author>
<title>Geo-Spatial Data Analysis</title>
<stream>Python</stream>
<price>4.95</price>
<publish_date>2020-07-01</publish_date>
<description>Learn geo Spatial data Analysis using Python.</description>
</Tutorial>
<Tutorial id="Tu102">...</Tutorial>
<Tutorial id="Tu103">...</Tutorial>
</Tutorials>
1. xml.etree.ElementTree (सुझावित)
पार्सिंग और सामग्री पढ़ना
import xml.etree.ElementTree as ET
tree = ET.parse('TutorialsList.xml')
root = tree.getroot()
print("ट्यूटोरियल सूची:")
for tutorial in root:
for child in tutorial:
print(f"{child.tag}: {child.text}")
आउटपुट
author: Vicky, Matthew title: Geo-Spatial Data Analysis stream: Python price: 4.95 publish_date: 2020-07-01 description: Learn geo Spatial data Analysis using Python. ... (बाकी ट्यूटोरियल)
एट्रिब्यूट्स प्राप्त करना
for tutorial in root.iter('Tutorial'):
print(tutorial.attrib) # {'id': 'Tu101'}, आदि
फिल्टरिंग (XPath-जैसा)
# कीमत 12.03 वाले ट्यूटोरियल
for tutorial in root.findall("./Tutorial/[price='12.03']"):
print(tutorial.attrib) # {'id': 'Tu102'}
2. xml.dom.minidom (DOM API)
from xml.dom.minidom import parse
DOMTree = parse('TutorialsList.xml')
collection = DOMTree.documentElement
tutorials = collection.getElementsByTagName("Tutorial")
print("***** ट्यूटोरियल *****")
for tut in tutorials:
stream = tut.getElementsByTagName('stream')[0]
price = tut.getElementsByTagName('price')[0]
print(f"Stream: {stream.childNodes[0].data}")
print(f"Price: {price.childNodes[0].data}")
आउटपुट
***** ट्यूटोरियल ***** Stream: Python Price: 4.95 Stream: Computer Science Price: 12.03 Stream: Data Science Price: 7.11
कौन सा चुनें?
| विशेषता | ElementTree | minidom |
|---|---|---|
| API शैली | पायथनिक, सरल | W3C DOM मानक |
| मेमोरी | कम (इटरेटिव पार्सिंग संभव) | पूरा ट्री मेमोरी में |
| XPath समर्थन | सीमित (findall) | बेहतर (xpath मॉड्यूल के साथ) |
| उपयोग | अधिकांश कार्यों के लिए | जटिल DOM मैनिपुलेशन |
सलाह: नए प्रोजेक्ट्स के लिए lxml लाइब्रेरी (तेज़, पूर्ण XPath) या बिल्ट-इन ElementTree उपयोग करें।