我试图解析,我本来想抓住的字符串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的方式
您可以轻松地修改您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>
这里spam
是objlocation
新的价值。
最短的代码,我可以建议:
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')