Created
November 20, 2021 15:37
-
-
Save evtn/a716a532d844587d005f0846dd24b9cc to your computer and use it in GitHub Desktop.
full-fledged one-line 381 chars XML builder with text escaping, attribute name cleaning and self-closing empty tags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from wtfisthat import r | |
| svg = { | |
| "n": "svg", | |
| "c": [ | |
| { | |
| "n": "rect", | |
| "a": { | |
| "width": "100%", | |
| "height": "100%", | |
| "fill": "white" | |
| } | |
| }, | |
| { | |
| "n": "text", | |
| "c": ["lol"], | |
| "a": { | |
| "font-family": "Arial", | |
| "font-size": "38", | |
| } | |
| } | |
| ], | |
| } | |
| r(svg) # yields '<svg ><rect width="100%"height="100%"fill="white"/><text font-family="Arial"font-size="38">lol</text></svg>' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| render = lambda xml:[ | |
| render(xml) | |
| for replace, join in [[str.replace, ''.join]] | |
| for escape, ident in [[ | |
| lambda text: replace(replace(replace(text, '&', '&'), '>', '>'), '<', '<'), | |
| lambda tag: join( | |
| filter( | |
| lambda i: i.isalnum() or (i in ':-'), | |
| str(tag) | |
| ) | |
| ) | |
| ]] | |
| for render in [ | |
| lambda tag: escape(tag) if type(tag) == str else f"<{tag['n']} {attr_render(tag)}{tail(tag)}" | |
| ] | |
| for tail, attr_render in [[ | |
| lambda tag: f">{join(map(render, tag['c']))}</{tag['n']}>" if 'c' in tag else '/>', | |
| lambda tag: join([f'{ident(attr_key)}="{tag["a"][attr_key]}"'for attr_key in tag.get('a', {})]) | |
| ]] | |
| ][0] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| r=lambda j:[e(j)for a,b in[[str.replace,''.join]]for c,d in[[lambda h:a(a(a(h,'&','&'),'>','>'),'<','<'),lambda h:b(filter(lambda i:i.isalnum()+(i in':-'),str(h)))]]for e in[lambda h:c(h)if str==type(h)else f"<{h['n']} {g(h)}{f(h)}"]for f,g in[[lambda h:f">{b(map(e,h['c']))}</{h['n']}>"if'c'in h else'/>',lambda h:b([f'{d(k)}="{h["a"][k]}"'for k in h.get('a',{})])]]][0] |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
js version with 308 characters: