Create xml with multiple root elements from txt file

Viewed 209

Im confused to convert content from .xml to .txt. Already I've dealt with conversion txt to xml, but problem with xml to txt seems to be harder.

App should take all values from child element and assign them into a list. The problem is that xml file has multiple roots elements (know that is invalid format) F.e: sample.xml looks as follows:

<row>
    <col>One</col>
    <col>Two</col>
    <col>Three</col>
</row>
<row>
    <col>John</col>
    <col>Mark</col>
    <col>Elise</col>
</row>

As the result sample.txt should looks as follows:

One Two Three
John Mark Elise

During writing this post i came with an idea but it looks ugly (especially with deleting col tag from line). Do you have any better ideas to get a values from child element |col|?

My code:

def convert_xml_to_txt(self):
        words_list = []
        with open(self.filename) as fxml:
            while True:
                line = fxml.readline()
                if line:
                    if line.startswith('<row'):
                        pass
                    else:
                        words_list.append(line[5:-7].strip()) #delete tags <col> from line
                else:
                    self.generate_txt_file(words_list)
                    break
1 Answers

There is a couple of libraries that you can use: one is untangle and can be installed by pip like pip install untangle:

import untangle
obj = untangle.parse('path/to/file.xml')

or you can use xmltodict helpful library:

import xmltodict

with open('path/to/file.xml') as fd:
    doc = xmltodict.parse(fd.read())

For more information look at This link.

Related