1 # This file is part of jack_mixer
3 # Copyright (C) 2006 Nedko Arnaudov <nedko@arnaudov.name>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; version 2 of the License
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 import xml
.dom
.minidom
21 from serialization
import SerializationBackend
24 class XmlSerializationError(Exception):
28 class InvalidDocumentTypeError(XmlSerializationError
):
32 class XmlSerialization(SerializationBackend
):
33 def get_root_serialization_object(self
, name
):
34 self
.doc
= xml
.dom
.getDOMImplementation().createDocument(
35 xml
.dom
.EMPTY_NAMESPACE
, name
, None
37 return XmlSerializationObject(self
.doc
, self
.doc
.documentElement
)
39 def get_root_unserialization_object(self
, name
):
40 if name
!= self
.doc
.documentElement
.nodeName
:
42 return XmlSerializationObject(self
.doc
, self
.doc
.documentElement
)
44 def get_child_serialization_object(self
, name
, backend_object
):
45 child
= self
.doc
.createElement(name
)
46 backend_object
.element
.appendChild(child
)
47 return XmlSerializationObject(self
.doc
, child
)
50 file.write(self
.doc
.toprettyxml())
52 def load(self
, file, name
):
53 self
.doc
= xml
.dom
.minidom
.parse(file)
55 document_type
= self
.doc
.documentElement
.nodeName
56 if document_type
!= name
:
57 raise InvalidDocumentTypeError("Document type '%s' not supported." % document_type
)
60 class XmlSerializationObject
:
61 def __init__(self
, doc
, element
):
63 self
.element
= element
65 def add_property(self
, name
, value
):
66 self
.add_property_as_attribute(name
, value
)
68 def add_property_as_attribute(self
, name
, value
):
69 self
.element
.setAttribute(name
, value
)
71 # def add_property_as_child_element(self, name, value):
72 # child = self.doc.createElement(name)
73 # value = self.doc.createTextNode(value)
74 # child.appendChild(value)
75 # self.element.appendChild(child)
78 child_elements
= self
.element
.childNodes
80 for child
in child_elements
:
81 if child
.nodeType
== child
.ELEMENT_NODE
:
82 childs
.append(XmlSerializationObject(self
.doc
, child
))
85 def get_properties(self
):
86 properties
= self
.element
.attributes
88 for i
in range(properties
.length
):
89 dictionary
[properties
.item(i
).name
] = properties
.item(i
).nodeValue
92 def serialization_name(self
):
93 return self
.element
.nodeName