Skip to content

Instantly share code, notes, and snippets.

@evtn
Created November 20, 2021 15:37
Show Gist options
  • Select an option

  • Save evtn/a716a532d844587d005f0846dd24b9cc to your computer and use it in GitHub Desktop.

Select an option

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
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>'
render = lambda xml:[
render(xml)
for replace, join in [[str.replace, ''.join]]
for escape, ident in [[
lambda text: replace(replace(replace(text, '&', '&amp;'), '>', '&gt;'), '<', '&lt;'),
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]
r=lambda j:[e(j)for a,b in[[str.replace,''.join]]for c,d in[[lambda h:a(a(a(h,'&','&amp;'),'>','&gt;'),'<','&lt;'),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]
@evtn
Copy link
Author

evtn commented Nov 20, 2021

js version with 308 characters:

let r=j=>{let[a,b,c,d,e,f,g]=[(h,i,j)=>h.replace(i,j),h=>h.join(''),h=>a(a(a(h,'&','&amp;'),'>','&gt;'),'<','&lt;'),h=>b(h.match(/[A-Z:-]/gi)),h=>(typeof h=="string")?c(h):`<${h.n} ${g(h)}${f(h)}`,h=>h.c?`>${b(h.c.map(e))}</${h.n}>`:'/>',h=>b(Object.keys(h.a||{}).map(k=>`${d(k)}="${h.a[k]}"`))];return e(j)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment