Python extract data from file and write to another
Question: I'm new in python and need help. I have a file and want to extract text to
another file.

The input file looks like this:

    
    
    <Datei Kennung="4bc78" Titel="Morgen 1" Bereich="I847YP"> Morgen 1
    
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    
    </Datei>
    <Datei Kennung="469" Titel="Trop Hall W " Bereich="izr"> Trop Hall W
    
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.    
    
    
    </Datei>
    

For the first area in my file i need as output the file Morgen 1.txt which
contains this:

    
    
    Morgen 1
    
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    Here is text, contains numbers and text.
    

I got from other user this code:

    
    
    import re
    REG_PARSE=re.compile(r'<Datei[^>]*Titel="\s*([^"]*?)\s*"[^>]*>\s*\1\s*(.*?</Datei>',re.dotall)
    with open(filename) as infile:
    for outfilename, text = REG_PARSE.finditer(infile.read()):
        with open('%s.txt'%outfilename,'w') as outf:
            outf.write(text)
    

but it does not work


Answer: See if this works for you:

    
    
    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    from xml.dom import minidom
    xmldoc  = minidom.parse('/path/to/file')
    items   = xmldoc.getElementsByTagName('Datei') 
    
    for s in items:
        if s.attributes['Titel'].value == "Morgen 1":
            with open("Morgen 1.txt", "w") as fileOutput:
                listLines = [   line.strip()
                                for line in s.firstChild.nodeValue.strip().split("\n")
                                if line.strip()
                                ]
    
                fileOutput.write("\n".join(listLines))
                break
    

