Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 526db66

Browse files
committed
Added ability to add namespaces parsed upon input in to_xml() and to_xml_file(); updated _get_namespace_def accordingly
1 parent 6ac1de8 commit 526db66

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

maec/__init__.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,11 @@ def to_xml(self, include_namespaces=True, namespace_dict=None,
211211
namespace_def = ""
212212

213213
if include_namespaces:
214+
# Update the namespace dictionary with namespaces found upon import
215+
if namespace_dict and self.__input_namespaces__:
216+
namespace_dict.update(self.__input_namespaces__)
217+
elif not namespace_dict and self.__input_namespaces__:
218+
namespace_dict = self.__input_namespaces__
214219
namespace_def = self._get_namespace_def(namespace_dict)
215220

216221
if not pretty:
@@ -223,6 +228,11 @@ def to_xml(self, include_namespaces=True, namespace_dict=None,
223228

224229
def to_xml_file(self, filename, namespace_dict=None):
225230
"""Export an object to an XML file. Only supports Package or Bundle objects at the moment."""
231+
# Update the namespace dictionary with namespaces found upon import
232+
if namespace_dict and self.__input_namespaces__:
233+
namespace_dict.update(self.__input_namespaces__)
234+
elif not namespace_dict and self.__input_namespaces__:
235+
namespace_dict = self.__input_namespaces__
226236
out_file = open(filename, 'w')
227237
out_file.write("<?xml version='1.0' encoding='UTF-8'?>\n")
228238
self.to_obj().export(out_file, 0, namespacedef_ = self._get_namespace_def(namespace_dict))
@@ -238,16 +248,18 @@ def _get_namespace_def(self, additional_ns_dict=None):
238248

239249
namespaces = self._get_namespaces()
240250

241-
if additional_ns_dict:
242-
for ns, prefix in additional_ns_dict.iteritems():
243-
namespaces.update([Namespace(ns, prefix)])
244-
245251
# if there are any other namepaces, include xsi for "schemaLocation"
246252
# also, include the MAEC default vocabularies schema by default
247253
if namespaces:
248254
namespaces.update([maecMETA.lookup_prefix('xsi')])
249255
namespaces.update([maecMETA.lookup_prefix('maecVocabs')])
250256

257+
if namespaces and additional_ns_dict:
258+
namespace_list = [x.name for x in namespaces if x]
259+
for ns, prefix in additional_ns_dict.iteritems():
260+
if ns not in namespace_list:
261+
namespaces.update([Namespace(ns, prefix)])
262+
251263
if not namespaces:
252264
return ""
253265

0 commit comments

Comments
 (0)