Search code examples
pythonxmlminidom

Modify (Change specific elements) XML file with minidom in python


I have n xml file in which I want to change three elements. It's the first, eighth and tenth <string> element. so the easiest approach, I guess, would be like this (But I am open to any other suggestions, Thanks!!):

DOM = xml.dom.minidom
doc = DOM.parse(open(FILENAME))

a = doc.getElementsByTagName('string')
for i in range(len(a)):
    if i == 0:
        a[i] = new Element with new Text
    if i == 7:
        a[i] = new Element with new Text
    if i == 9:
        a[i] = new Element with new Text

Thats my file basically:

<plist version="1.0">
<dict>
    <key></key>
    <string>CHANGE THIS</string>
    <string>aaa</string>
    <key>aaa</key>
        <dict>
            <key>aaa</key>
            <dict>
                <key>aaa</key>
                <string>aaa</string>
                <key>aaa</key>
                <false/>
            </dict>
            <key>aaa</key>
            <dict>
                <key>aaa</key>
                <string>aaaa.png</string>
                <key>aaa</key>
                <string>aaa</string>
                <key>aaa</key>
                <string>aaa</string>
            </dict>
        </dict>
        <key></key>
        <true/>
        <key></key>
        <string></string>
    <key></key>
    <string>CHANGE THIS</string>
    <key></key>
    <string></string>
    <key></key>
    <string>AND CHANGE THIS</string>
    <key></key>
    <string></string>
    <key></key>
    <string></string>
    <key></key>
    <key></key>
    <true/>
    <key></key>
    <string></string>
    <key></key>
    <key></key>
</dict>
</plist>

Solution

  • I got this finally figured out myself.

    a = doc.getElementsByTagName('string')
    for i in range(len(a)):
        if i == 0:
            a[i].firstChild.nodeValue = myvalue1
        if i == 7:
            a[i].firstChild.nodeValue = myvalue2
        if i == 9:
            a[i].firstChild.nodeValue = myvalue3