【问题标题】:Appending some data to specific XML Tag from txt file to xml in Python将一些数据附加到特定的 XML 标记,从 txt 文件到 Python 中的 xml
【发布时间】:2017-10-27 18:30:33
【问题描述】:
下面是在我的 txt 文件中我想将它粘贴到下面的 xml 文件中的资源标签内没有来自 txt 文件的标签有什么方法可以做到这一点我尝试了很多但失败了我想基本上将它附加到 xml 文件.
TXT 文件
<resources>
<format fieldOrder="upper first" frameDuration="200/5000s" height="1080" id="3305" name="FFVideoFormat1080i50" width="1920"></format>
</resource>
XML 文件
<resource>
<asset id="r28" name="Poldark_S03E02_2tk_UK_Music_20170428.L" uid="1F74A">
</asset>
</resources>
【问题讨论】:
标签:
xml
python-3.x
xml-parsing
elementtree
【解决方案1】:
你说过你想“追加”,但我认为你想把format元素放在resource元素中。如果这是正确的,那么重要的是要了解根元素的 insert 方法。
在这里,我将字符串转换为 xml 树。然后我确定这些树的根。完成后,我选择了txt_file 树的第一个孩子并将其插入到xml_file 树的根的孩子列表的位置0。
from lxml import etree
txt_file = '''\
<resources>
<format fieldOrder="upper first" frameDuration="200/5000s" height="1080" id="3305" name="FFVideoFormat1080i50" width="1920"></format>
</resources>'''
xml_file = '''\
<resource>
<asset id="r28" name="Poldark_S03E02_2tk_UK_Music_20170428.L" uid="1F74A"></asset>
</resource>'''
txt_tree = etree.fromstring(txt_file)
xml_tree = etree.fromstring(xml_file)
txt_root = txt_tree.getroottree().getroot()
xml_root = xml_tree.getroottree().getroot()
xml_root.insert(0, txt_root.getchildren()[0])
print (etree.tostring(xml_tree))
结果:
b'<resource>\n\t<format fieldOrder="upper first" frameDuration="200/5000s" height="1080" id="3305" name="FFVideoFormat1080i50" width="1920"/>\n<asset id="r28" name="Poldark_S03E02_2tk_UK_Music_20170428.L" uid="1F74A"/>\n</resource>'