是的,你可以用lxml
来做到这一点。
我建议你使用模板XML并填充它。
模板:
<Item>
<Info>
<Name/>
</Info>
<Genres>
<Genre/>
</Genres>
</Item>
from lxml import etree
tree = etree.parse("template.xml")
然后往里面:
entries = [
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'}]
for entry in entries:
xpath = entry["Path"]
node = tree.xpath(xpath)[0]
node.text = entry['Value']
注:不是 “路径”,我更愿意 “的XPath”
如果你不想要的模板,你可以像这样产生整个树形结构:
from lxml import etree
entries = [
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'}]
root = None
for entry in entries:
path = entry["Path"]
parts = path.split("/")
xpath_list = ["/" + parts[0]] + parts[1:]
curr = root
for xpath in xpath_list:
name = xpath.strip("/")
if curr is None:
root = curr = etree.Element(name)
else:
nodes = curr.xpath(xpath)
if nodes:
curr = nodes[0]
else:
curr = etree.SubElement(curr, name)
curr.text = entry["Value"]
print(etree.tostring(root, pretty_print=True))
结果是:
<Item>
<Info>
<Name>Body HD</Name>
</Info>
<Genres>
<Genre>Action</Genre>
</Genres>
</Item>
当然,也有局限性。
那么第一个节点在路径中总是相同的? –
@PadraicCunningham这是正确的 – David542