Python LMF library
 All Classes Namespaces Files Functions Variables
xml_format.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 """! @package utils
4 """
5 
6 from utils.io import open_write, ENCODING
7 
8 try:
9  from xml.etree.cElementTree import Element, SubElement, parse, dump, ElementTree, fromstring, tostring, XML
10 except ImportError:
11  from xml.etree.ElementTree import Element, SubElement, parse, dump, ElementTree, fromstring, tostring, XML
12 
13 def prettify(element, encoding=ENCODING):
14  """! @brief Return a pretty-printed XML string for the given XML element.
15  @param element An XML element.
16  @param encoding Encoding mode. Default value is 'utf-8'.
17  @return A Python string containing the printed version of the XML element.
18  """
19  from xml.dom import minidom
20  rough_string = tostring(element, encoding=encoding)
21  reparsed = minidom.parseString(rough_string)
22  return reparsed.toprettyxml(indent=" ", encoding=encoding)
23 
24 def write_result(element, filename, encoding=ENCODING):
25  """! @brief Write an XML element into a pretty XML output file.
26  @param element An XML element.
27  @param filename The name of the XML file to write with full path, for instance 'output.xml'.
28  @param encoding Encoding mode. Default value is 'utf-8'.
29  """
30  unicode_str = prettify(element, encoding=encoding)
31  output_file = open_write(filename, encoding=encoding)
32  output_file.write(unicode_str.decode(encoding))
33  output_file.close()
34 
35 def parse_xml(filename):
36  """! @brief Parse an XML file.
37  @param filename The name of the XML file to parse with full path, for instance 'input.xml'.
38  @return The root XML element.
39  """
40  tree = parse(filename)
41  root = tree.getroot()
42  return root
def write_result
Write an XML element into a pretty XML output file.
Definition: xml_format.py:24
def parse_xml
Parse an XML file.
Definition: xml_format.py:35
def prettify
Return a pretty-printed XML string for the given XML element.
Definition: xml_format.py:13
def open_write
Open file in write mode (automatically decode file in unicode).
Definition: io.py:47