def parse_el(stream): stack = [] root = None for ev in xmltok2.tokenize(stream): typ = ev[0] if typ == xmltok2.START_TAG: el = Element() el.tag = ev[2] if not stack: root = el else: stack[-1]._children.append(el) stack.append(el) elif typ == xmltok2.ATTR: stack[-1].attrib[ev[2]] = ev[3] elif typ == xmltok2.TEXT: stack[-1].text = ev[1] elif typ == xmltok2.END_TAG: if stack[-1].tag != ev[2]: raise ParseError("mismatched tag: /%s (expected: /%s)" % (ev[1][1], stack[-1].tag)) stack.pop() return root
def __call__(self, *args): buf = uio.StringIO() buf.write("<?xml version='1.0'?>\n<methodCall>\n<methodName>") buf.write(self.name) buf.write("</methodName>\n<params>\n") for a in args: buf.write("<param><value>") if isinstance(a, int): buf.write("<int>%s</int>" % a) else: raise NotImplementedError buf.write("</value></param>\n") buf.write("</params>\n</methodCall>\n") if self.server.verbose: print(buf.getvalue()) body = buf.getvalue().encode() f = urlopen(self.server.uri, body, "POST") try: #print(f.read()) f = f.makefile() tokenizer = xmltok2.tokenize(f) xmltok2.gfind( tokenizer, lambda ev: ev[0] == xmltok2.START_TAG and ev[2] == "value") ev = next(tokenizer) assert ev[0] == xmltok2.START_TAG typ = ev[2] ev = next(tokenizer) assert ev[0] == xmltok2.TEXT val = ev[1] if typ == "boolean": assert val in ("0", "1") return val == "1" else: assert NotImplementedError finally: #print("*", f.read()) f.close()
import xmltok2 as xmltok dir = "." if "/" in __file__: dir = __file__.rsplit("/", 1)[0] tokenizer = xmltok.tokenize(open(dir + "/test_text_of.xml")) text = xmltok.text_of(tokenizer, "val") assert text == "foo" text = xmltok.text_of(tokenizer, "val") assert text == "bar" # Will match even namespaced tag text = xmltok.text_of(tokenizer, "val") assert text == "kaboom" # Match specifically namespaced tag text = xmltok.text_of(tokenizer, ("ns", "val")) assert text == "kaboom2" try: text = xmltok.text_of(tokenizer, "val") assert False except StopIteration: pass
['PI', 'xml', None, None], ['ATTR', '', 'version', '1.0'], ['START_TAG', 's', 'Envelope', None], ['ATTR', 'xmlns', 's', 'http://schemas.xmlsoap.org/soap/envelope/'], [ 'ATTR', 's', 'encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/' ], ['START_TAG', 's', 'Body', None], ['START_TAG', 'u', 'GetConnectionTypeInfo', None], ['ATTR', 'xmlns', 'u', 'urn:schemas-upnp-org:service:WANIPConnection:1'], ['TEXT', 'foo bar\n baz\n \n', None, None], ['END_TAG', 'u', 'GetConnectionTypeInfo', None], ['END_TAG', 's', 'Body', None], ['START_TAG', '', 'foo', None], ['ATTR', '', 'attr', 'singlequote'], ['END_TAG', '', 'foo', None], ['START_TAG', '', 'foo2', None], ['END_TAG', '', 'foo2', None], ['END_TAG', 's', 'Envelope', None], ] dir = "." if "/" in __file__: dir = __file__.rsplit("/", 1)[0] ex = iter(expected) for i in xmltok2.tokenize(open(dir + "/test.xml")): print(i) assert i == next(ex)