1

I have an xml file as such:

<root processName="someName" >
    <Property name="FirstProp" value="one" />
    <Property name="SecondProp" value="two" />
    <Property name="ThirdProp" value="three" />
</root>

Is it possible, using xmltodict, to find the Property "SecondProp" without knowing the specific index and change value from "two" to "seventeen"? (below)

Code:

import os
import xmltodict

text_file = open("testxml.xml", "r")
tst = text_file.read()

obj = xmltodict.parse(tst)

print(obj['root']['@processName'])
print(obj['root']['Property'][0])
print(obj['root']['Property'][1])
print(obj['root']['Property'][2])

Output:

someName
OrderedDict([('@name', 'FirstProp'), ('@value', 'one')])
OrderedDict([('@name', 'SecondProp'), ('@value', 'two')])
OrderedDict([('@name', 'ThirdProp'), ('@value', 'three')])

1 Answers1

0

You can iterate through obj['root']['Property'] and find the one you're looking for. The way XML is parsed with xmltodict, makes obj['root']['Property'] a list and not a dict.

Example:

for x in obj['root']['Property']:
    if x['@name'] == 'SecondProp':
        # do whatever you want
jwodder
  • 54,758
  • 12
  • 108
  • 124
NinjaKitty
  • 638
  • 7
  • 17