Skip to content
Advertisement

Convert dynamic XML file to CSV file – Python

I would like to convert this XML file:

JavaScript

to this CSV file:

JavaScript

I can have several bodies of ID structures.

I use the lxml library.

I tried with the xpath method and for loop but I can only get the ID but not the rest. The problem is the second for loop, but I don’t know how to deal with the values of “date” and “time”…

JavaScript

Here the result:

JavaScript

Thanks for your time.

Advertisement

Answer

To use lxml, you can simply pass the string as html(). By using the xpath //record/ts (starting with double backslash), you can fetch all your ts results. The main id can be accessed by calling .getparent() and then the attribute.

To convert xml to csv, I would recommend using the python package csv. You can use normal file writer. However csv write handles a lot of issues and it’s cleaner.

In general, you have one method that handles everything. I would recommend splitting the logic into functions. Think Single Responsibility. Also the solution below I’ve converted the xml nodes into a NamedTupple and then write the namedTupple to csv. It’s a lot easier to maintain/ read. (i.e Theres one place that sets the header text and one place populate the data).

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement