Passed
Push — master ( 698cc1...9545fa )
by
unknown
02:41 queued 46s
created

gvm.xml._GmpCommandFactory.delete_target_command()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-3.0-or-later
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
import defusedxml.lxml as secET
20
21
from lxml import etree
22
23
class XmlCommandElement:
24
25
    def __init__(self, element):
26
        self._element = element
27
28
    def add_element(self, name, text=None, attrs=None):
29
        node = etree.SubElement(self._element, name, attrib=attrs)
30
        node.text = text
31
        return XmlCommandElement(node)
32
33
    def set_attribute(self, name, value):
34
        self._element.set(name, value)
35
36
    def set_attributes(self, attrs):
37
        """Set several attributes at once.
38
39
        Arguments:
40
            attrs (dict): Attributes to be set on the element
41
        """
42
        for key, value in attrs.items():
43
            self._element.set(key, value)
44
45
    def append_xml_str(self, xml_text):
46
        """Append a xml element in string format."""
47
        node = secET.fromstring(xml_text)
48
        self._element.append(node)
49
50
    def to_string(self):
51
        return etree.tostring(self._element).decode('utf-8')
52
53
    def __str__(self):
54
        return self.to_string()
55
56
57
class XmlCommand(XmlCommandElement):
58
59
    def __init__(self, name):
60
        super().__init__(etree.Element(name))
61
62
63
def pretty_print(xml):
64
    """Prints beautiful XML-Code
65
66
    This function gets an object of list<lxml.etree._Element>
67
    or directly a lxml element.
68
    Print it with good readable format.
69
70
    Arguments:
71
        xml: List<lxml.etree.Element> or directly a lxml element
72
    """
73
    if isinstance(xml, list):
74
        for item in xml:
75
            if etree.iselement(item):
76
                print(etree.tostring(item, pretty_print=True).decode('utf-8'))
77
            else:
78
                print(item)
79
    elif etree.iselement(xml):
80
        print(etree.tostring(xml, pretty_print=True).decode('utf-8'))
81