MCPcopy Create free account
hub / github.com/ActiveState/code / xml

Class xml

recipes/Python/576445_ElementTree_Wrapper/recipe-576445.py:32–207  ·  view source on GitHub ↗

Usage: xml(tag, child, ..., attr = value, ...) returns new element with specified child elements and attributes xml(tag, text, child, ..., attr = value, ...) returns new element with specified text, child elements, and attributes xml(literal) returns new element for

Source from the content-addressed store, hash-verified

30PREFIX_PAT = re.compile('(\{.*\})')
31
32class xml(object):
33 """
34 Usage:
35 xml(tag, child, ..., attr = value, ...)
36 returns new element with specified child elements and attributes
37 xml(tag, text, child, ..., attr = value, ...)
38 returns new element with specified text, child elements, and attributes
39 xml(literal)
40 returns new element for literal xml string
41 xml(xmlable)
42 returns xmlable.__xml__()
43
44 Example:
45 from xmlwrapper import xml
46 table_elt = xml('table', xml('tr',xml('td',"header",colspan = "2")),
47 xml('tr',xml('td',xml('b',"bold text")),
48 xml('td',"plain text")))
49 table_elt['border'] = "1"
50 open("test.html","w").write(str(xml('html',xml('body',table_elt))))
51 print table_elt.navlist('tr')
52
53 Example of __xml__ interface:
54 class xmldict(dict):
55 def __xml__(self):
56 xml_elt = xml('dict')
57 for key in self:
58 xml_elt.append(xml('dictent',xml('key',str(key)),
59 xml('value',str(self[key]))))
60 return xml_elt
61
62 e = xmldict()
63 e['foo'] = 'bar'
64 print xml(e)
65 """
66 def __new__(cls,tag,thing = None,*args,**kwargs):
67 if hasattr(tag,'__xml__'):
68 return tag.__xml__()
69 self = object.__new__(xml)
70 if cElementTree.iselement(tag):
71 self.__content = tag
72 elif isinstance(tag,cElementTree.ElementTree):
73 self.__content = tag.getroot()
74 elif is_file(tag):
75 self.__content = cElementTree.parse(tag).getroot()
76 elif isinstance(tag,str) and len(tag) > 0 and tag[0] == '<':
77 self.__content = cElementTree.fromstring(tag)
78 else:
79 if type(tag) != str:
80 raise TypeError("Cannot convert %s object to xml" % str(type(tag)))
81 self.__content = cElementTree.fromstring('<%s/>' % tag)
82 if is_text(thing) or type(thing) == int:
83 self.__content.text = text(thing)
84 elif thing != None:
85 self.append(xml(thing))
86 for subthing in args:
87 self.append(xml(subthing))
88 for key,value in kwargs.items():
89 if key == '__class' or key == 'klass':

Callers 8

__new__Method · 0.70
pretty_listMethod · 0.70
itereltsMethod · 0.70
findMethod · 0.70
findallMethod · 0.70
__xml__Method · 0.70
test1Function · 0.70
test2Function · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected