1
|
1 |
|
from lxml import etree |
2
|
|
|
|
3
|
1 |
|
from .transform import SchemaCollector, cfdi_schemas, validate_xsd |
4
|
1 |
|
from .utils import ScalarMap, parser |
5
|
1 |
|
from .transform.objectify import cfdi_objectify |
6
|
1 |
|
from .transform.xmlify import cfdi_xmlify |
7
|
|
|
|
8
|
|
|
|
9
|
1 |
|
class XElement(ScalarMap): |
10
|
1 |
|
tag = None |
11
|
|
|
|
12
|
1 |
|
def to_xml(self, validate=False, include_schema_location=False) -> etree.Element: |
13
|
1 |
|
xml = cfdi_xmlify[self.tag](self) |
14
|
|
|
|
15
|
1 |
|
if validate or include_schema_location: |
16
|
1 |
|
col = SchemaCollector() |
17
|
1 |
|
cfdi_schemas[self.tag](col, self) |
18
|
1 |
|
if validate: |
19
|
1 |
|
validate_xsd(xml, col.base) |
20
|
1 |
|
if include_schema_location: |
21
|
1 |
|
xml.attrib['{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'] = " ".join(col.schemas) |
22
|
|
|
|
23
|
1 |
|
return xml |
24
|
|
|
|
25
|
1 |
|
def process(self, validate=False) -> 'XElement': |
26
|
1 |
|
return XElement.from_xml(self.to_xml(validate=validate)) |
27
|
|
|
|
28
|
1 |
|
def copy(self) -> 'XElement': |
29
|
1 |
|
el = XElement(super().copy()) |
30
|
1 |
|
el.tag = self.tag |
31
|
1 |
|
return el |
32
|
|
|
|
33
|
1 |
|
@classmethod |
34
|
1 |
|
def from_xml(cls, xml_root) -> 'XElement': |
35
|
1 |
|
obj = cfdi_objectify[xml_root.tag](cls, xml_root) |
36
|
1 |
|
if not isinstance(obj, XElement): |
37
|
1 |
|
obj = XElement(obj) |
38
|
1 |
|
obj.tag = xml_root.tag |
39
|
1 |
|
return obj |
40
|
|
|
|
41
|
1 |
|
@classmethod |
42
|
1 |
|
def from_file(cls, filename) -> 'XElement': |
43
|
1 |
|
return cls.from_xml(etree.parse(filename, parser=parser).getroot()) |
44
|
|
|
|
45
|
1 |
|
@classmethod |
46
|
1 |
|
def from_string(cls, string) -> 'XElement': |
47
|
1 |
|
return cls.from_xml(etree.fromstring(string, parser=parser)) |
48
|
|
|
|
49
|
1 |
|
def xml_write(self, target, pretty_print=False, xml_declaration=True): |
50
|
1 |
|
xml = self.to_xml() |
51
|
1 |
|
et = etree.ElementTree(xml) |
52
|
1 |
|
et.write( |
53
|
|
|
target, |
54
|
|
|
xml_declaration=xml_declaration, |
55
|
|
|
encoding="UTF-8", |
56
|
|
|
pretty_print=pretty_print |
57
|
|
|
) |
58
|
|
|
|
59
|
1 |
|
def xml_bytes(self, pretty_print=False, xml_declaration=True, validate=False, include_schema_location=False) -> bytes: |
60
|
1 |
|
xml = self.to_xml(validate=validate, include_schema_location=include_schema_location) |
61
|
1 |
|
return etree.tostring(xml, xml_declaration=xml_declaration, encoding="UTF-8", pretty_print=pretty_print) |
62
|
|
|
|
63
|
|
|
def __repr__(self): |
64
|
|
|
# return '%s.%s(%s)' % (self.__class__.__module__, |
65
|
|
|
# self.__class__.__qualname__, |
66
|
|
|
# f'{repr(self.tag)}, {super().__repr__()}') |
67
|
|
|
return '%s(%s)' % ( |
68
|
|
|
self.__class__.__qualname__, |
69
|
|
|
f'{dict.__repr__(self)}' |
70
|
|
|
) |
71
|
|
|
|