| 1 |
#!/usr/bin/python2 |
| 2 |
|
| 3 |
# xml.g |
| 4 |
# |
| 5 |
# Amit J. Patel, August 2003 |
| 6 |
# |
| 7 |
# Simple (non-conforming, non-validating) parsing of XML documents, |
| 8 |
# based on Robert D. Cameron's "REX" shallow parser. It doesn't |
| 9 |
# handle CDATA and lots of other stuff; it's meant to demonstrate |
| 10 |
# Yapps, not replace a proper XML parser. |
| 11 |
|
| 12 |
%% |
| 13 |
|
| 14 |
parser xml: |
| 15 |
token nodetext: r'[^<>]+' |
| 16 |
token attrtext_singlequote: "[^']*" |
| 17 |
token attrtext_doublequote: '[^"]*' |
| 18 |
token SP: r'\s' |
| 19 |
token id: r'[a-zA-Z_:][a-zA-Z0-9_:.-]*' |
| 20 |
|
| 21 |
rule node: |
| 22 |
r'<!--.*?-->' {{ return ['!--comment'] }} |
| 23 |
| r'<!\[CDATA\[.*?\]\]>' {{ return ['![CDATA['] }} |
| 24 |
| r'<!' SP* id '[^>]*>' {{ return ['!doctype'] }} |
| 25 |
| '<' SP* id SP* attributes SP* {{ startid = id }} |
| 26 |
( '>' nodes '</' SP* id SP* '>' {{ assert startid == id, 'Mismatched tags <%s> ... </%s>' % (startid, id) }} |
| 27 |
{{ return [id, attributes] + nodes }} |
| 28 |
| '/\s*>' {{ return [id, attributes] }} |
| 29 |
) |
| 30 |
| nodetext {{ return nodetext }} |
| 31 |
|
| 32 |
rule nodes: {{ result = [] }} |
| 33 |
( node {{ result.append(node) }} |
| 34 |
) * {{ return result }} |
| 35 |
|
| 36 |
rule attribute: id SP* '=' SP* |
| 37 |
( '"' attrtext_doublequote '"' {{ return (id, attrtext_doublequote) }} |
| 38 |
| "'" attrtext_singlequote "'" {{ return (id, attrtext_singlequote) }} |
| 39 |
) |
| 40 |
|
| 41 |
rule attributes: {{ result = {} }} |
| 42 |
( attribute SP* {{ result[attribute[0]] = attribute[1] }} |
| 43 |
) * {{ return result }} |
| 44 |
|
| 45 |
%% |
| 46 |
|
| 47 |
if __name__ == '__main__': |
| 48 |
tests = ['<!-- hello -->', |
| 49 |
'some text', |
| 50 |
'< bad xml', |
| 51 |
'<br />', |
| 52 |
'< spacey a = "foo" / >', |
| 53 |
'<a href="foo">text ... </a>', |
| 54 |
'<begin> middle </end>', |
| 55 |
'<begin> <nested attr=\'baz\' another="hey"> foo </nested> <nested> bar </nested> </begin>', |
| 56 |
] |
| 57 |
print |
| 58 |
print '____Running tests_______________________________________' |
| 59 |
for test in tests: |
| 60 |
print |
| 61 |
try: |
| 62 |
parser = xml(xmlScanner(test)) |
| 63 |
output = '%s ==> %s' % (repr(test), repr(parser.node())) |
| 64 |
except (yappsrt.SyntaxError, AssertionError), e: |
| 65 |
output = '%s ==> FAILED ==> %s' % (repr(test), e) |
| 66 |
print output |