【发布时间】:2020-01-07 08:10:03
【问题描述】:
我希望帮助我从 XML 文件中提取特定的 XML 文件块,并使用 Python 3.8 将其复制到另一个文件中。我尝试了类似问题的所有答案。不幸的是,我无法做到。任何帮助将不胜感激。
示例 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<bookstores>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<miscellaneous id="1000611004" />
</bookstore>
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<miscellaneous id="1000611067" />
</bookstore>
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<miscellaneous id="3450611067" />
</bookstore>
</bookstores>
示例 Python 脚本
这里,我正在检查 orderIds 列表中的项目是否与 miscellaneous 的 id 属性匹配。如果匹配,则需要将整个 XML 块复制到另一个文件。
orderIds = ["1000611004", "1000611067"]
mytree = ET.parse(xmlFile)
myroot = mytree.getroot()
for x in myroot.iter():
if(x.tag == 'miscellaneous'):
attribute = x.attrib
idToCheck = attribute['id']
for id in orderIds:
if(id == idToCheck):
--Confused Part To Be Filled--
预期输出
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<miscellaneous id="1000611004" />
</bookstore>
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<miscellaneous id="1000611067" />
</bookstore>
【问题讨论】:
标签: python python-3.x xml xml-parsing elementtree