I have a path "a/b/c/d" and value for d is Apple.
I would like to create a function to transform the path into XML format like:
<a>
<b>
<c>
<d> Apple </d>
</c>
</b>
</a>
CodePudding user response:
A simple string-based solution could be
tags = "a/b/c/d".split('/')
value = 'Apple'
out = ''
for t in tags:
out = f'<{t}>'
out = value
for t in reversed(tags):
out = f'</{t}>'
print(out) # <a><b><c><d>Apple</d></c></b></a>
CodePudding user response:
Solution using xml.etree.ElementTree, the advantage is that you can assign values to any element
from xml.etree import ElementTree
def xpath_to_xml(current_node, path, text_values):
parts = path.split("/")
while parts:
target = 0
part = parts.pop(0)
cur = -1
for child in current_node.getchildren():
if child.tag == part:
cur = 1
if cur == target:
node = child
break
else:
for _ in range(target - cur):
new = ElementTree.Element(part)
if part in text_values:
new.text = text_values[part]
current_node.append(new)
current_node = new
def main():
doc = ElementTree.Element("root")
xpath_to_xml(doc, "a/b/c/d", {"d": "Apple"})
print(ElementTree.tostring(doc))