Update README.rst
[PyCIM.git] / PyCIM / RDFXMLWriter.py
blobe5a3c4e9634e2661495da113691dcde76804c409
1 # Copyright (C) 2010-2011 Richard Lincoln
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to
5 # deal in the Software without restriction, including without limitation the
6 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 # sell copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 # IN THE SOFTWARE.
21 import logging
23 from time import time
25 from CIM15 import nsURI, nsPrefix
27 from PyCIM.SimpleXMLWriter import XMLWriter
29 nsPrefixRDF = "rdf"
30 nsRDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
32 logger = logging.getLogger(__name__)
34 def cimwrite(d, source, encoding="utf-8"):
35 """CIM RDF/XML serializer.
37 @type d: dict
38 @param d: Map of URIs to CIM objects.
39 @type source: File or file-like object.
40 @param source: This object must implement a C{write} method
41 that takes an 8-bit string.
42 @type encoding: string
43 @param encoding: Character encoding defaults to "utf-8", but can also
44 be set to "us-ascii".
45 @rtype: bool
46 @return: Write success.
47 """
48 # Start the clock
49 t0 = time()
51 w = XMLWriter(source, encoding)
53 # Write the XML declaration.
54 w.declaration()
56 # Add a '#' suffix to the CIM namespace URI if not present.
57 nsCIM = nsURI if nsURI[-1] == "#" else nsURI + "#"
59 # Start the root RDF element and declare namespaces.
60 xmlns = {u"xmlns:%s" % nsPrefixRDF: nsRDF, u"xmlns:%s" % nsPrefix: nsCIM}
61 rdf = w.start(u"%s:RDF" % nsPrefixRDF, xmlns)
63 # Iterate over all UUID, CIM object pairs in the given dictionary.
64 for uuid, obj in d.items():
65 w.start(u"%s:%s" % (nsPrefix, obj.__class__.__name__),
66 {u"%s:ID" % nsPrefixRDF: obj.UUID})
68 mro = obj.__class__.mro()
69 mro.reverse()
71 # Serialise attributes.
72 for klass in mro[2:]: # skip 'object' and 'Element'
73 attrs = [a for a in klass._attrs if a not in klass._enums]
74 for attr in attrs:
75 val = getattr(obj, attr)
76 if val != klass._defaults[attr]:
77 w.element(u"%s:%s.%s" % (nsPrefix, klass.__name__, attr),
78 str(val))
80 # Serialise enumeration data-types.
81 for klass in mro[2:]: # skip 'object' and 'Element'
82 enums = [a for a in klass._attrs if a in klass._enums]
83 for enum in enums:
84 val = getattr(obj, enum)
85 dt = klass._enums[enum]
86 w.element(u"%s:%s.%s" % (nsPrefix, klass.__name__, enum),
87 attrib={u"%s:resource" % nsPrefixRDF:
88 u"%s%s.%s" % (nsCIM, dt, val)})
90 # Serialise references.
91 for klass in mro[2:]: # skip 'object' and 'Element'
92 # FIXME: serialise 'many' references.
93 refs = [r for r in klass._refs if r not in klass._many_refs]
94 for ref in refs:
95 val = getattr(obj, ref)
96 if val is not None:
97 w.element(u"%s:%s.%s" % (nsPrefix, klass.__name__, ref),
98 attrib={u"%s:resource" % nsPrefixRDF:
99 u"#%s" % val.UUID})
101 w.end()
103 # Close the root RDF element.
104 w.close(rdf)
106 # Flush the output stream.
107 w.flush()
109 logger.info("%d CIM objects serialised in %.2fs.", len(d), time() - t0)
112 if __name__ == "__main__":
113 from RDFXMLReader import cimread
114 from PrettyPrintXML import xmlpp
116 logging.basicConfig(level=logging.INFO)
118 d = cimread("Test/Data/EDF_AIGUE_v9.xml")
119 # d = cimread("Test/Data/ENTSOE_16_BE_EQ.xml")
120 tmp = "/tmp/cimwrite.xml"
121 cimwrite(d, tmp)
123 print(xmlpp(tmp))