diff options
author | Nick Mathewson <nickm@torproject.org> | 2008-11-22 19:13:10 +0000 |
---|---|---|
committer | Nick Mathewson <nickm@torproject.org> | 2008-11-22 19:13:10 +0000 |
commit | cff6c8bac612ae4ed598ef222ada02d3a83ecaa1 (patch) | |
tree | 4a64951ef30e6795ef2dcebff20c302751885227 /lib/thandy/encodeToXML.py | |
parent | d077d211bbfabeecf0b175df6bfb8e4e96a30747 (diff) |
Add a quick and dirty thandy-client json2xml command. I am going to regret this someday.
git-svn-id: file:///home/or/svnrepo/updater/trunk@17366 55e972cd-5a19-0410-ae62-a4d7a52db4cd
Diffstat (limited to 'lib/thandy/encodeToXML.py')
-rw-r--r-- | lib/thandy/encodeToXML.py | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lib/thandy/encodeToXML.py b/lib/thandy/encodeToXML.py new file mode 100644 index 0000000..4387c88 --- /dev/null +++ b/lib/thandy/encodeToXML.py @@ -0,0 +1,70 @@ +# Copyright 2008 The Tor Project, Inc. See LICENSE for licensing information. + +import re + +def xml_str_encoder(s): + s = s.replace("&", "&") + s = s.replace("<", "<") + s = s.replace(">", ">") + return s + +def isAsciiName(s): + """ + Return true iff s is pure-ascii, and a syntactically valid XML name. + + >>> isAsciiName("a") + True + >>> isAsciiName("ab.-dc") + True + >>> isAsciiName("") + False + >>> isAsciiName(".foo") + False + """ + return re.match(r'^[A-Za-z\_\:][A-Za-z0-9\_\:\-\.]*$', s) != None + +def _encodeToXML(obj, outf, indent=0): + if isinstance(obj, basestring): + outf(xml_str_encoder(obj)) + elif obj is True: + outf("true") + elif obj is False: + outf("false") + elif obj is None: + outf("null") + elif isinstance(obj, (int,long)): + outf(str(obj)) + elif isinstance(obj, (tuple, list)): + istr = " "*indent + outf("<list>\n") + for item in obj: + outf("<item>") + _encodeToXML(item, outf) + outf("</item> ") + outf("</list>\n") + elif isinstance(obj, dict): + outf("<dict>\n") + for k,v in sorted(obj.items()): + isAscii = isAsciiName(k) + if isAscii: + outf("<%s>"%k) + _encodeToXML(v, outf) + outf("</%s>\n"%k) + else: + outf("<dict-entry><key>%s</key><val>"%xml_str_encoder(k)) + _encodeToXML(v, outf) + outf("</val></dict-entry>\n") + outf("</dict>\n") + else: + raise thandy.FormatException("I can't encode %r"%obj) + +def encodeToXML(obj, outf=None): + """Convert a json-encodable object to a quick-and-dirty XML equivalent.""" + result = None + if outf == None: + outf = result.append + + _encodeToXML(obj, outf) + if result is not None: + return "".join(result) + |