Skip to content

Python:xml.etree.ElementTree

Example

OPM의 Configure file을 읽기 위한 class 샘플은 아래와 같다.

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

참고로 XML파일은 아래와 같다.

<?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

References


  1. Python_xml_use.pdf