用路径和值编写xml [英] Write xml with a path and value
本文介绍了用路径和值编写xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个路径和值的列表,像这样:
I have a list of paths and values, something like this:
[
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'},
]
我想构建完整的xml结构,即:
And I want to build out the full xml structure, which would be:
<Item>
<Info>
<Name>Body HD</Name>
</Info>
<Genres>
<Genre>Action</Genre>
</Genres>
</Item>
有没有办法用lxml
做到这一点?或者我该如何构建一个函数来填充推断的路径?
Is there a way to do this with lxml
? Or how could I build a function to fill in the inferred paths?
推荐答案
您可以执行以下操作:
l = [
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'},
]
import lxml.etree as et
root_node = l[0]["Path"].split("/", 1)[0]
tree = et.fromstring("<{}></{}>".format(root_node, root_node))
for dct in l:
nodes = iter(dct["Path"].split("/")[1:])
# catch path like Item/Foo where there is only one child.
nxt_child = child = et.Element(next(nodes))
for node in nodes:
# keep adding nodes
nxt_child = et.Element(node)
child.append(nxt_child)
# set value to last node.
nxt_child.text = dct["Value"]
# append it to the tree.
tree.append(child)
print(et.tostring(tree))
哪个会给你:
<Item>
<Info>
<Name>Body HD</Name>
</Info>
<Genres>
<Genre>Action</Genre>
</Genres>
</Item>
您知道Item
是根节点,并且是每个Path中的第一个节点,因此首先使用该节点创建树,然后随便添加到树中.
You know Item
is the root node and the first in every Path, so first create a tree using that node and then just add to the tree as you go.
这篇关于用路径和值编写xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文