Python Read XML file (DOM Example)
By:Roy.LiuLast updated:2019-08-17
In this example, we will show you how to read an XML file and print out its values, via Python xml.dom.minidom.
1. XML File
A simple XML file, later parse it with Python minidom.
staff.xml
<?xml version="1.0"?> <company> <name>Mkyong Enterprise</name> <staff id="1001"> <nickname>mkyong</nickname> <salary>100,000</salary> </staff> <staff id="1002"> <nickname>yflow</nickname> <salary>200,000</salary> </staff> <staff id="1003"> <nickname>alex</nickname> <salary>20,000</salary> </staff> </company>
2. DOM Example 1
A simple Python minidom example.
dom-example.py
from xml.dom import minidom doc = minidom.parse("staff.xml") # doc.getElementsByTagName returns NodeList name = doc.getElementsByTagName("name")[0] print(name.firstChild.data) staffs = doc.getElementsByTagName("staff") for staff in staffs: sid = staff.getAttribute("id") nickname = staff.getElementsByTagName("nickname")[0] salary = staff.getElementsByTagName("salary")[0] print("id:%s, nickname:%s, salary:%s" % (sid, nickname.firstChild.data, salary.firstChild.data))
Output
Mkyong Enterprise id:1001, nickname:mkyong, salary:100,000 id:1002, nickname:yflow, salary:200,000 id:1003, nickname:alex, salary:20,000
3. DOM Example 2
Yet another minidom example.
dom-example2.py
from xml.dom import minidom doc = minidom.parse("staff.xml") def getNodeText(node): nodelist = node.childNodes result = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: result.append(node.data) return ''.join(result) name = doc.getElementsByTagName("name")[0] print("Node Name : %s" % name.nodeName) print("Node Value : %s \n" % getNodeText(name)) staffs = doc.getElementsByTagName("staff") for staff in staffs: sid = staff.getAttribute("id") nickname = staff.getElementsByTagName("nickname")[0] salary = staff.getElementsByTagName("salary")[0] print("id:%s, nickname:%s, salary:%s" % (sid, getNodeText(nickname), getNodeText(salary)))
Output
Node Name : name Node Value : Mkyong Enterprise id:1001, nickname:mkyong, salary:100,000 id:1002, nickname:yflow, salary:200,000 id:1003, nickname:alex, salary:20,000
4. Project Demo
References
From:一号门
COMMENTS