在Python中将一些数据从txt文件附加到特定的XML标记到xml

问题描述 投票:-1回答:1

下面是在我的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个回答
0
投票

你已经说过要追加'但我想你想把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>'
© www.soinside.com 2019 - 2024. All rights reserved.