Q:

How to copy a particular XML record block from XML file using Python?

I would like to have help in extracting a particular XML file block from an XML file and copy it to another file using Python 3.8. I tried all the answers of similar questions. Unfortunately, I could not make it. Any help will be greatly appreciated.
Sample XML File
<?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>

Sample Python Script
Here, I am checking whether the items in orderIds list is matching with the id attribute of miscellaneous. If matching, that entire XML block need to be copied to another file.
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--

Output Expected
<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>

A:

You can try:
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'))

