【发布时间】:2015-10-15 07:44:07
【问题描述】:
我正在尝试使用此代码将一个简单的信息添加到 xml 树中,该信息在表格中。每个文件都有我需要添加到其中的 id。 corresp 字典有文件名和 id 对。 xml中已经有一个空元素,叫idno[@type='TM'],我需要在里面输入对应的id号。
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 列”
我的第二个可能相关的问题是,当它工作时,我无法将输出写入文件。理想情况下,我想简单地将其写回我正在修改的文件中。
非常感谢您对此提供任何建议。
【问题讨论】:
-
try ---from bs4 import BeautifulSoup import os DIR = 'files/' root = os.path.abspath(DIR) corresp = {"00100004":"362375", "00100005":" 362376", "00100006":"362377", "00100007":"362378"} for fileName, tm in corresp.iteritems(): soup = BeautifulSoup(open(os.path.join(root,"fileName",". xml"))) tmid = soup.find("idno", type="TM") tmid.append(tm) 打印汤
标签: python xml io beautifulsoup