1

私はPythonを初めて使用します。Pythonを使用して次のことを達成する方法を知りたいです。

XML ファイルがあり、そのファイルを開いて、タグに新しい値を設定する必要があります。

更新中に障害が発生した場合、ファイルは元の状態になります

ファイル名: ABC.xml

<Root>
<Location>
<city>WrongCity</city>
<state>WrongState</state>
<country>WrongCountry</country>
</Location>
</Root>

ファイルパスを関数に渡す。

def correctValues(filepath)
    # update the wrong information 
    try:
        set city = MYcity
        set state = somevalue
        set country = somedata
    except:
        Rollback to original file

値の更新中に問題がなければ、元のファイルを修正した値で更新する必要があります。

期待される出力:

<Root>
<Location>
<city>MYcity</city>
<state>somevalue</state>
<country>somedata</country>
</Location>
</Root>

問題が発生した場合は、ファイルをロールバックする必要があります。

前もって感謝します。

4

1 に答える 1

0

最も簡単な方法は、おそらく次のとおりです。

  1. ライブラリを呼び出して、XML を解析して実際のノードのツリーにします。

  2. 必要に応じてそのツリーを変更します。と

  3. 新しいツリーを書き戻します。

"bs4" (いくつか問題がありますが、多くの場合十分です) を使用すると、次のようになります。

from bs4 import BeautifulSoup as BS
import codecs

badCityDict = {  # List of corrections
    "Washingtun": "Washington",
    "Bolton": "Boston"
}

# Second parameter to constructor picks what parser bs4 should use.
tree = bs4(codecs.open(myfile, mode='r', encoding='utf-8'), 'lxml')

changeCount = 0
cityNodes = tree.find_all('city')
for cn in cityNodes:
    cnText = cn.string.strip()
    if cnText in badCityDict:
        cn.string.replace_with(badCityDict[cnText])
        changeCount += 1

### same thing for state, country, and so on...

if (changeCount > 0):
    print tree.prettify()
于 2015-10-08T21:35:02.147 に答える