July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Julius Welby
Parsers of tabular data or comma-separated values (CSV) files usually output a list of lists. Converting these into XML allows them to be manipulated with XSLT and other XML tools. Example 12-2 takes a list of equal-length lists and converts it into XML (or, optionally, into an HTML table).
Example 12-2. Converting a list of equal-length lists into XML
# LL2XML.py -- Version 0.3 -- 15 July 2001 # http://www.outwardlynormal.com/python/ll2XML.htm for the full docs import string # Set up exceptions class Error(Exception): def _ _init_ _(self, errcode, heading_num = 0, sublist_length = 0): self.errcode = errcode if self.errcode == "Length Error - Sublists": self.message = ["All the sublists must be of uniform length."] elif self.errcode == "Heading Error - heading/sublist mismatch": self.message = ["There is at least one empty heading item.\n", "Please supply non-empty headings."] elif self.errcode == "Length Error: heading/sublist mismatch": self.message = ["Number of headings =", 'heading_num', "\n", "Number of elements in sublists =", 'sublist_length', "\n", "These numbers must be equal."] else: self.message = [""] self.errmsg = string.join(self.message) def _ _str_ _(self): return self.errmsg def escape(s): """ Replace special characters '&', "'", '<', '>', and '"' with XML entities. """ s = s.replace("&", "&") # Must be done first! s = s.replace("'", "'") s = s.replace("<", "<") s = s.replace(">", ...Read now
Unlock full access