Implementing serialisation of CIM objects.
[PyCIM.git] / src / PyCIM / xmlpp.py
blob342dcc01d786953a2ee60de3a9e35659f7dc7078
1 """Pretty print an XML document.
3 LICENCE:
4 Copyright (c) 2008, Fredrik Ekholdt
5 All rights reserved.
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice,
11 this list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
17 * Neither the name of Fredrik Ekholdt nor the names of its contributors may be used to
18 endorse or promote products derived from this software without specific prior
19 written permission.
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE."""
33 import sys as _sys
34 import re as _re
36 def _usage(this_file):
37 return """SYNOPSIS: pretty print an XML document
38 USAGE: python %s <filename> \n""" % this_file
40 def _pprint_line(indent_level, line, width=100, output=_sys.stdout):
41 if line.strip():
42 start = ""
43 number_chars = 0
44 for l in range(indent_level):
45 start = start + " "
46 number_chars = number_chars + 1
47 try:
48 elem_start = _re.findall("(\<\W{0,1}\w+:\w+) ?", line)[0]
49 elem_finished = _re.findall("([?|\]\]/]*\>)", line)[0]
50 #should not have *
51 attrs = _re.findall("(\S*?\=\".*?\")", line)
52 output.write(start + elem_start)
53 number_chars = len(start + elem_start)
54 for attr in attrs:
55 if (attrs.index(attr) + 1) == len(attrs):
56 number_chars = number_chars + len(elem_finished)
57 if (number_chars + len(attr) + 1) > width:
58 output.write("\n")
59 for i in range(len(start + elem_start) + 1):
60 output.write(" ")
61 number_chars = len(start + elem_start) + 1
62 else:
63 output.write(" ")
64 number_chars = number_chars + 1
65 output.write(attr)
66 number_chars = number_chars + len(attr)
67 output.write(elem_finished + "\n")
68 except IndexError:
69 #give up pretty print this line
70 output.write(start + line + "\n")
73 def _pprint_elem_content(indent_level, line, output=_sys.stdout):
74 if line.strip():
75 for l in range(indent_level):
76 output.write(" ")
77 output.write(line + "\n")
79 def _get_next_elem(data):
80 start_pos = data.find("<")
81 end_pos = data.find(">") + 1
82 retval = data[start_pos:end_pos]
83 stopper = retval.rfind("/")
84 if stopper < retval.rfind("\""):
85 stopper = -1
86 single = (stopper > -1 and ((retval.find(">") - stopper) < (stopper - retval.find("<"))))
88 ignore_excl = retval.find("<!") > -1
89 ignore_question = retval.find("<?") > -1
91 if ignore_excl:
92 cdata = retval.find("<![CDATA[") > -1
93 if cdata:
94 end_pos = data.find("]]>")
95 if end_pos > -1:
96 end_pos = end_pos + len("]]>")
98 elif ignore_question:
99 end_pos = data.find("?>") + len("?>")
100 ignore = ignore_excl or ignore_question
102 no_indent = ignore or single
104 #print retval, end_pos, start_pos, stopper > -1, no_indent
105 return start_pos, \
106 end_pos, \
107 stopper > -1, \
108 no_indent
110 def get_pprint(xml, indent=4, width=80):
111 """Returns the pretty printed xml """
112 class out:
113 output = ""
115 def write(self, string):
116 self.output += string
117 out = out()
118 pprint(xml, output=out, indent=indent, width=width)
120 return out.output
123 def pprint(xml, output=_sys.stdout, indent=4, width=80):
124 """Pretty print xml.
125 Use output to select output stream. Default is sys.stdout
126 Use indent to select indentation level. Default is 4 """
127 data = xml
128 indent_level = 0
129 start_pos, end_pos, is_stop, no_indent = _get_next_elem(data)
130 while ((start_pos > -1 and end_pos > -1)):
131 _pprint_elem_content(indent_level, data[:start_pos].strip(),
132 output=output)
133 data = data[start_pos:]
134 if is_stop and not no_indent:
135 indent_level = indent_level - indent
136 _pprint_line(indent_level,
137 data[:end_pos - start_pos],
138 width=width,
139 output=output)
140 data = data[end_pos - start_pos:]
141 if not is_stop and not no_indent :
142 indent_level = indent_level + indent
144 if not data:
145 break
146 else:
147 start_pos, end_pos, is_stop, no_indent = _get_next_elem(data)
150 if __name__ == "__main__":
151 if "-h" in _sys.argv or "--help" in _sys.argv:
152 _sys.stderr.write(_usage(_sys.argv[0]))
153 _sys.exit(1)
154 if len(_sys.argv) < 2:
155 _sys.stderr.write(_usage(_sys.argv[0]))
156 _sys.exit(1)
157 else:
158 filename = _sys.argv[1]
159 fh = open(filename)
161 pprint(fh.read(), output=_sys.stdout, indent=4, width=80)