Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Last active June 26, 2024 19:11
Show Gist options
  • Save simonLeary42/2da95f816bed08b75d995b48eeb65f22 to your computer and use it in GitHub Desktop.
Save simonLeary42/2da95f816bed08b75d995b48eeb65f22 to your computer and use it in GitHub Desktop.
outputs an obscure subset of XML where the content of a given object must be either a string, or more objects, but not both. Also, the XML output attributes "__content__" and "__children__" are forbidden. Each child in the __children__ list must be a dict, with exactly one key: the data type of the child.
def dict2xml(x: dict, indent=0) -> str:
assert isinstance(x, dict)
assert len(x) == 1
datatype = list(x.keys())[0]
assert re.fullmatch(r"[a-zA-Z0-9_]+", datatype)
data = x[datatype]
body = ""
if "__content__" in data:
assert isinstance(data["__content__"], str)
body += f"{' '*(indent+2)}{data['__content__']}"
del data["__content__"]
if "__children__" in data:
for child in data["__children__"]:
body += "\n"
body += dict2xml(child, indent=indent + 2)
del data["__children__"]
open_bracket = f"<{datatype}"
for attr_name, attr_value in data.items():
assert re.fullmatch(r"[a-zA-Z0-9_]+", attr_name)
open_bracket += f" {attr_name}="
if isinstance(attr_value, str):
open_bracket += f'"{attr_value}"'
else:
open_bracket += str(attr_value)
open_bracket += ">"
close_bracket = f"</{datatype}>"
if body:
if "\n" not in body.strip():
return f"{' '*indent}{open_bracket}{body.strip()}{close_bracket}"
else:
return f"{' '*indent}{open_bracket}{body}\n{' '*indent}{close_bracket}"
else:
return f"{' '*indent}{open_bracket} />"
FooType:
attr1: "foo"
attr2: "bar"
__children__:
- FooType:
__content__: "string"
- FooType:
__children__:
- FooType:
attr4: 123
- FooType:
attr5: 456
<FooType attr1="foo" attr2="bar">
<FooType>string</FooType>
<FooType>
<FooType attr4=123> />
<FooType attr5=456> />
</FooType>
</FooType>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment