-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyxml.py
More file actions
40 lines (31 loc) · 976 Bytes
/
Copy pathmyxml.py
File metadata and controls
40 lines (31 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/python
# coding:utf-8
from xml.parsers.expat import ParserCreate
class MySaxHandler(object):
def start(self, name, attrs):
print('sax:start_element:%s ,attrs:%s' % (name, str(attrs)))
def end(self, name):
print('sax:end_element: %s' % name)
def char_data(self, text):
print('sax:char_data: %s' % text)
xml = r'''<?xml version="1.0"?>
<ol>
<li><a href="/python">Python</a></li>
<li><a href="/ruby">Ruby</a></li>
</ol>
'''
handler = MySaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start
parser.EndElementHandler = handler.end
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)
def encode(s):
return s.replace('&', '&').replace('<', '<').replace('>', '>')
L = []
L.append(r'<?xml version="1.0"?>')
L.append(r'<root>')
L.append(encode('some & data'))
L.append(r'</root>')
print ''.join(L)