Retrieve and parse XML data using Python [AJAX]
Program to demonstrate the process of fetching and parsing the XML data using Python language.
XML File
<?xml version="1.0" encoding="ISO8859-1" ?>
<portfolio>
<stock exchange="nyse">
<name>zacx corp</name>
<symbol>ZCXM</symbol>
<price>28.875</price>
</stock>
<stock exchange="nasdaq">
<name>zaffymat inc</name>
<symbol>ZFFX</symbol>
<price>92.250</price>
</stock>
</portfolio>
Code
import urllib
from xml.dom import minidom
url = "http://www.xmlfiles.com/examples/portfolio.xml"
dom = minidom.parse(urllib.urlopen(url))
# dom.getElementsByTagName returns NodeList
stocks = dom.getElementsByTagName("stock")
for stock in stocks:
exchange = stock.getAttribute("exchange")
name = stock.getElementsByTagName("name")[0]
symbol = stock.getElementsByTagName("symbol")[0]
price = stock.getElementsByTagName("price")[0]
print("exchange:%s, name:%s, symbol:%s, price:%s" %
(exchange, name.firstChild.data, symbol.firstChild.data, price.firstChild.data))
Output
exchange:nyse, name:zacx corp, symbol:ZCXM, price:28.875
exchange:nasdaq, name:zaffymat inc, symbol:ZFFX, price:92.250
-
Previous -
Next
This website is made possible by displaying online advertisements to our visitors.
Please consider supporting by disabling your ad blocker.
Please consider supporting by disabling your ad blocker.
loading comments...