编辑XML与Python(Edit XML with python)

2019-10-21 17:51发布

我试图解析,我本来想抓住的字符串XML文件objlocation并更改字符串的内容。

这是XML文件我的内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<publish show="STATE">

    <pubgroup objtype="ELE" location="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.xml">

        <member objidx="15283942" objlabel="anm" objlocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.anm"/>

        <member objidx="15283952" objlabel="fbx" objlocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001_M_WALK_None.fbx"/>

        <member objidx="15283962" objlabel="mov" objlocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.mov"/>

        <member objidx="15283972" objlabel="libraryinfo" objlocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.json"/>

        <member objidx="15283982" objlabel="thumbnail" objlocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.mng"/>

    </pubgroup>
</publish>

我试图.firstChild.childNodes[]它打印出内容作为我的XML文件。 这是XML文件的列表,我试图解析其中,它的格式是差不多的。

我试图做到这一点是Python的方式

Answer 1:

您可以轻松地修改您xml使用文件ElementTree的API

from xml.etree.ElementTree import parse
doc = parse('data.xml')
root = doc.getroot()
for t in root.iterfind('pubgroup/member'):
    t.attrib['objlocation'] = "spam"

doc.write('output.xml', xml_declaration=True)

iterfind方法返回一个generator的功能,而不是list ,这是非常方便,如果你有xml文件非常大

产量

<?xml version='1.0' encoding='us-ascii'?>
<publish show="STATE">

    <pubgroup location="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.xml" objtype="ELE">

        <member objidx="15283942" objlabel="anm" objlocation="spam" />

        <member objidx="15283952" objlabel="fbx" objlocation="spam" />

        <member objidx="15283962" objlabel="mov" objlocation="spam" />

        <member objidx="15283972" objlabel="libraryinfo" objlocation="spam" />

    <member objidx="15283982" objlabel="thumbnail" objlocation="spam" />

</pubgroup>

这里spamobjlocation新的价值。



Answer 2:

最短的代码,我可以建议:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
root = tree.parse('test.txt') # root represents <publish> tag

for member in root.findall('pubgroup/member'):
    print member.attrib['objlocation']

输出:

/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.anm
/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001_M_WALK_None.fbx
/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.mov
/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.json
/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.mng

要更改:

for member in root.findall('pubgroup/member'):
    member.attrib['objlocation'] = 'changed'
tree.write('output.txt')


文章来源: Edit XML with python