Python:xml.etree.ElementTree
lastmod 2019-03-04created 2015-03-3113 edits
Example
A sample class for reading the Configure file of OPM is shown below.
class Config:
def __init__(self):
self.protocol = "ssh"
self.user = "root"
self.host = "127.0.0.1"
self.port = "22"
self.remote = "/var/opm"
pass
def read(self, filename = CONFIGPATH):
try:
doc = ET.parse(filename)
root = doc.getroot()
# check the root tag.
if root.tag != TAG_ROOT or root.attrib[ATTR_VERSION] != MIN_VERSION:
return False
config = root.find(TAG_CONFIG)
self.protocol = config.find(TAG_PROTOCOL).text
self.user = config.find(TAG_USER).text
self.host = config.find(TAG_HOST).text
self.port = config.find(TAG_PORT).text
self.remote = config.find(TAG_REMOTE).text
except (ET.ParseError, AttributeError) as e:
#print e.args[0]
return False
return True
def get(self):
return self.protocol + "://" + self.user + "@" + \
self.host + ":" + self.port + self.remote
For reference, the XML file is as follows.
<?xml version="1.0" encoding="utf-8" ?>
<opm version="0.1">
<config>
<protocol>ssh</protocol>
<user>root</user>
<host>host.com</host>
<port>22</port>
<remote>/var/opm</remote>
</config>
</opm>
Parsing a string
from xml.etree import ElementTree
tree = ElementTree.ElementTree(ElementTree.fromstring(<your_xml_string>))
to string
import xml.etree.ElementTree as ET
tag_root = ET.Element('root')
tag_root.set('attr', 'name')
tag_root.text = 'Content'
tag_child = ET.Element('child')
tag_child.set('attr', 'name')
tag_root.append(tag_child)
ET.tostring(tag_root)
Pretty printing XML
import xml.dom.minidom
xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
See also
Favorite site
- xml.etree.ElementTree — The ElementTree XML API
- ElementTree Overview
- Jump to Python: XML processing with ElementTree
- Python - Handling XML via ElementTree #1
- An artistic encounter of Python and XML
- Python, Using XML 1
- How to handle XML documents with Python
- Python Tutorial ≫ XML ≫ DOM
- The Document Object Model API (xml.dom)
- Handling XML with Python
References
-
Python_xml_use.pdf ↩