我想要使用此代碼將添加到xml樹中的一個簡單的信息,我在表中。每個文件都有我需要添加到其中的ID。相應的字典具有文件名和id夫婦。在XML中已經有一個空元素,叫做idno [@ type ='TM'],我需要輸入相應的id號。Beautifulsoup xml
from bs4 import BeautifulSoup
DIR = 'files/'
corresp = {"00100004":"362375", "00100005":"362376", "00100006":"362377", "00100007":"362378"}
for fileName, tm in corresp.iteritems():
soup = BeautifulSoup(open(DIR + fileName + ".xml"))
tmid = soup.find("idno", type="TM")
tmid.append(tm)
print soup
我的第一個問題是:一段時間它的作品,一段時間後它說
tmid.append(tm)
AttributeError: 'NoneType' object has no attribute 'append'
我不知道爲什麼。昨天晚上我運行相同的示例代碼,現在它以這種方式抱怨。
我也曾嘗試etree
import xml.etree.ElementTree as ET
DIR = 'files/'
corresp = {"00100004":"362375", "00100005":"362376", "00100006":"362377", "00100007":"362378"}
for fileName, tm in corresp.iteritems():
f = open(DIR + fileName + ".xml")
tree = ET.parse(f)
tmid = tree.findall("//idno[@type='TM']")
tmid.append(tm)
tree.write('output.xml', encoding='utf-8', xml_declaration=True)
但它說:「沒有的元素中找到:第1行,列0」
我的第二個,可能相關的問題是,當它的工作,我是不是能夠將輸出寫入文件。理想情況下,我想簡單地將其寫回到我正在修改的文件中。
非常感謝您對此的任何建議。
嘗試---從BS4進口BeautifulSoup 進口OS DIR = '文件/' 根= os.path.abspath則(DIR) 對應於100 = { 「00100004」: 「362375」, 「00100005」: 「362376」, 「00100006」: 「362377」, 「00100007」: 「362378」} 給fileName,TM在corresp.iteritems(): 湯= BeautifulSoup(開放(OS。 path.join(root,「fileName」,「。xml」))) tmid = soup.find(「idno」,type =「TM」) tmid.append(tm) print soup – SIslam