Passed
Pull Request — master (#49)
by
unknown
01:42
created

gvm.xml.validate_xml_string()   A

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 14
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 defusedxml import DefusedXmlException
22
from lxml import etree
23
24
from gvm.errors import GvmError
25
26
27
class XmlCommandElement:
28
29
    def __init__(self, element):
30
        self._element = element
31
32
    def add_element(self, name, text=None, attrs=None):
33
        node = etree.SubElement(self._element, name, attrib=attrs)
34
        node.text = text
35
        return XmlCommandElement(node)
36
37
    def set_attribute(self, name, value):
38
        self._element.set(name, value)
39
40
    def set_attributes(self, attrs):
41
        """Set several attributes at once.
42
43
        Arguments:
44
            attrs (dict): Attributes to be set on the element
45
        """
46
        for key, value in attrs.items():
47
            self._element.set(key, value)
48
49
    def append_xml_str(self, xml_text):
50
        """Append a xml element in string format."""
51
        node = secET.fromstring(xml_text)
52
        self._element.append(node)
53
54
    def to_string(self):
55
        return etree.tostring(self._element).decode('utf-8')
56
57
    def __str__(self):
58
        return self.to_string()
59
60
61
class XmlCommand(XmlCommandElement):
62
63
    def __init__(self, name):
64
        super().__init__(etree.Element(name))
65
66
67
def pretty_print(xml):
68
    """Prints beautiful XML-Code
69
70
    This function gets a string containing the xml, an object of
71
    list<lxml.etree._Element> or directly a lxml element.
72
73
    Print it with good readable format.
74
75
    Arguments:
76
        xml (str, list or lxml.etree.Element): xml as string,
77
            List<lxml.etree.Element> or directly a lxml element
78
    """
79
    if isinstance(xml, list):
80
        for item in xml:
81
            if etree.iselement(item):
82
                print(etree.tostring(item, pretty_print=True).decode('utf-8'))
83
            else:
84
                print(item)
85
    elif etree.iselement(xml):
86
        print(etree.tostring(xml, pretty_print=True).decode('utf-8'))
87
    elif isinstance(xml, str):
88
        tree = secET.fromstring(xml)
89
        print(etree.tostring(tree, pretty_print=True).decode('utf-8'))
90
91
92
def validate_xml_string(xml_string):
93
    """Checks if the passed string contains valid XML
94
95
    Raises a GvmError if the XML is invalid. Otherwise the function just
96
    returns.
97
98
    Raises:
99
        GvmError: The xml string did contain invalid XML
100
101
    """
102
    try:
103
        secET.fromstring(xml_string)
104
    except (DefusedXmlException, etree.LxmlError) as e:
105
        raise GvmError('Invalid XML', e) from e
106