用 python 编辑 XML

Edit XML with python

我正在尝试解析一个 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 个文件的列表,其格式大致相同。

我正在尝试以 pythonic 方式做到这一点

我可以建议的最短代码:

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')

您可以使用 ElementTree API

轻松修改 xml 文件
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 方法 returns 一个 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 新值。