编程语言
首页 > 编程语言> > 在python中以最少的方式修改(更改特定元素)XML文件

在python中以最少的方式修改(更改特定元素)XML文件

作者:互联网

我有我要更改三个元素的xml文件.
这是第一个,第八个和第十个< string>元件.因此,我想最简单的方法就是这样(但我愿意接受任何其他建议,谢谢!!):

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

那基本上是我的文件:

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

解决方法:

我终于明白了这一点.

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

标签:minidom,xml,python
来源: https://codeday.me/bug/20191201/2077767.html