Skip to content Skip to sidebar Skip to footer

Edit Xml With Python

I am trying to parse a xml file where I had wanted to grab the string of objlocation and change the contents of the string. This are the contents of the xml files I have:

Solution 1:

You can easily modify your xml file using the 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)

The iterfind method returns a generator function instead of list which is very convenient if your have xml file is very large

Output

<?xml version='1.0' encoding='us-ascii'?><publishshow="STATE"><pubgrouplocation="/user_data/STATE/ITEM/character/ANM/ANM_rig_WALK_sg_v001/ANM_rig_WALK_sg_v001.xml"objtype="ELE"><memberobjidx="15283942"objlabel="anm"objlocation="spam" /><memberobjidx="15283952"objlabel="fbx"objlocation="spam" /><memberobjidx="15283962"objlabel="mov"objlocation="spam" /><memberobjidx="15283972"objlabel="libraryinfo"objlocation="spam" /><memberobjidx="15283982"objlabel="thumbnail"objlocation="spam" /></pubgroup>

Here spam is objlocation new value.

Solution 2:

The shortest code I can suggest:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
root = tree.parse('test.txt') # root represents <publish> tagfor member in root.findall('pubgroup/member'):
    print member.attrib['objlocation']

Output:

/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

To make changes:

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

Post a Comment for "Edit Xml With Python"