Split one large .xml file in more .xml files (python)
Question: I've been trying to split one large .xml file in more .xml files in python for
a few days now. The thing is I haven't really succeeded yet. So here I am
asking for your help.

My large .xml file looks like this:

    
    
    <Root>
         <Testcase>
              <Info1>[]<Info1>
              <Info2>[]<Info2>
         </Testcase>
         <Testcase>
              <Info1>[]<Info1>
              <Info2>[]<Info2>
         <Testcase>
         ...
         ...
         ...
         <Testcase>
              <Info1>[]<Info1>
              <Info2>[]<Info2>
         <Testcase>
    </Root>
    

It has over 2000 children and what I would like to do is to parse this .xml
file and split in smaller .xml files with 100 children each. That would result
in 20 new .xml files.

How can I do that?

Thank you!

L.E.:

I've tried to parse the .xml file using xml.etree.ElementTree

    
    
    import xml.etree.ElementTree as ET
    file = open('Testcase.xml', 'r')
    tree = ET.parse(file)
    
    total_testcases = 0
    
    for Testcase in root.findall('Testcase'):
        total_testcases+=1
    
    nr_of_files = (total_testcases/100)+1
    
    for i in range(nr_of_files+1):
        tree.write('Testcase%d.xml' % (i), encoding="UTF-8")
    

The thing is I don't know how to specifically get only the Testcases and copy
them to another file...


Answer: Actually, root.findall('Testcase') will return a list of "Testcase" sub
elements. So what need to do is:

  1. create root 
  2. add sub elements to root.

Here is example:

    
    
    >>> tcs = root.findall('Testcase')
    >>> tcs
    [<Element 'Testcase' at 0x23e14e0>, <Element 'Testcase' at 0x23e1828>]
    >>> len(tcs)
    2
    >>> r = ET.Element('Root')
    >>> r.append(tcs[0])
    >>> ET.tostring(r, 'utf-8')
    '<Root><Testcase>\n          <Info1>[]</Info1>\n          <Info2>[]</Info2>\n     </Testcase>\n     </Root>'
    

