【问题标题】:How to copy a particular XML record block from XML file using Python?如何使用 Python 从 XML 文件中复制特定的 XML 记录块?
【发布时间】: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 列表中的项目是否与 miscellaneousid 属性匹配。如果匹配,则需要将整个 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


    【解决方案1】:

    你可以试试:

    tree = ET.parse('xmlfile')
    root = tree.getroot()
    orderIds = ["1000611004", "1000611067"]
    bookstore_nodes = root.findall('.//bookstore')
    with open('output.xml', 'w') as f:
        for bn in bookstore_nodes:
            misc_node = bn.findall('.//miscellaneous')
            if len(misc_node) > 0 and misc_node[0].attrib['id'] in orderIds:
                f.write(ET.tostring(bn).decode('utf-8'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多