【发布时间】:2017-03-31 05:27:22
【问题描述】:
我在本地文件中有 XML,它是最终消息的模板,该消息将 POSTed 发送到 REST 服务。该脚本在模板数据发布之前对其进行预处理。
所以模板看起来像这样:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<singleElement>
<subElementX>XYZ</subElementX>
</singleElement>
<repeatingElement id="11" name="Joe"/>
<repeatingElement id="12" name="Mary"/>
</root>
除了repeatingElement 标记需要替换为其他内容(脚本基于现有标记中的属性生成的 XML)之外,消息 XML 应该看起来相同。
到目前为止,这是我的脚本:
xmlData = None
with open('conf//test1.xml', 'r') as xmlFile:
xmlData = xmlFile.read()
xmlSoup = BeautifulSoup(xmlData, 'html.parser')
repElemList = xmlSoup.find_all('repeatingelement')
for repElem in repElemList:
print("Processing repElem...")
repElemID = repElem.get('id')
repElemName = repElem.get('name')
# now I do something with repElemID and repElemName
# and no longer need it. I would like to replace it with <somenewtag/>
# and dump what is in the soup object back into a string.
# is it possible with BeautifulSoup?
我可以用其他东西替换重复元素,然后将汤对象转储到我可以发布到我的 REST API 的新字符串中吗?
注意:我使用的是html.parser,因为我使用的是can't get the xml parser to work,但它工作正常,理解HTML 比解析XML 更容易。
【问题讨论】:
标签: python xml beautifulsoup