我有一條路徑“a/b/c/d”,d 的值是 Apple。
我想創建一個函式來將路徑轉換為 ??XML 格式,例如:
<a>
<b>
<c>
<d> Apple </d>
</c>
</b>
</a>
uj5u.com熱心網友回復:
使用xml.etree.ElementTree的解決方案,優點是您可以將值分配給任何元素
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))
uj5u.com熱心網友回復:
一個簡單的基于字串的解決方案可能是
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>
uj5u.com熱心網友回復:
就像下面的代碼一樣簡單:-)
import xml.etree.ElementTree as ET
def path_to_xml(path: str, last_element_value: str):
elements = path.split('/')
root = None
parent = None
for idx, element in enumerate(elements):
if idx == 0:
root = ET.Element(element)
parent = root
else:
parent = ET.SubElement(parent, element)
if idx == len(elements) - 1:
parent.text = last_element_value
return root
xml = path_to_xml('a/b/c/d', 'apple')
ET.dump(xml)
輸出
<a>
<b>
<c>
<d>apple</d>
</c>
</b>
</a>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517705.html
標籤:Pythonxml
