File: xml.py

package info (click to toggle)
pcs 0.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,148 kB
  • sloc: python: 238,810; xml: 20,833; ruby: 13,203; makefile: 1,595; sh: 484
file content (52 lines) | stat: -rw-r--r-- 1,282 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import xml.dom.minidom

from lxml import etree


def dom_get_child_elements(element):
    return [
        child
        for child in element.childNodes
        if child.nodeType == xml.dom.minidom.Node.ELEMENT_NODE
    ]


def etree_to_str(tree):
    # etree returns string in bytes: b'xml'
    # so there is bytes to str conversion
    return etree.tostring(tree, pretty_print=True).decode()


def str_to_etree(string):
    return etree.fromstring(string)


class XmlManipulation:
    @classmethod
    def from_file(cls, file_name):
        return cls(etree.parse(file_name).getroot())

    @classmethod
    def from_str(cls, string):
        return cls(str_to_etree(string))

    def __init__(self, tree):
        self.tree = tree

    @staticmethod
    def __append_to_child(element, xml_string):
        element.append(etree.fromstring(xml_string))

    def append_to_first_tag_name(self, tag_name, *xml_string_list):
        for xml_string in xml_string_list:
            self.__append_to_child(
                self.tree.find(".//{0}".format(tag_name)), xml_string
            )
        return self

    def __str__(self):
        return etree_to_str(self.tree)


def get_xml_manipulation_creator_from_file(file_name):
    return lambda: XmlManipulation.from_file(file_name)