Full tag in to_xml pandas in any case

Full tag in to_xml pandas in any case

Problem Description:

I have a code like this:

    data_to_string = data_from_table.to_xml(path_or_buffer= file_name + ".xml", index=False,
                                            root_name="convoy", row_name="vehicle", xml_declaration=False)

It works fine with files containing several rows but if there is nothing to export, i have only

<convoy/>

in my .xml.

How can I fix the code to have:

<convoy>
</convoy>

in any cases?

Solution – 1

This behavior is hard-coded into the xml-library.

Your requirement can be fulfilled by checking whether there are rows in your dataframe and, if not, by creating an empty html-string (here and here) instead and writing that to the output.

Be aware that <convoy/> and <convoy></convoy> are equivalent in xml.

Here is a fully working example:

import pandas as pd
from lxml import etree

file_name = "test"
path = file_name + ".xml"
root_name = "convoy"
row_name = "vehicle"

data_from_table = pd.DataFrame()
if len(data_from_table.index) > 0:
    data_to_string = data_from_table.to_xml(
        path_or_buffer=path,
        index=False,
        root_name=root_name,
        row_name=row_name,
        xml_declaration=False,
    )
else:
    elem = etree.Element(root_name)
    empty_xml = etree.tostring(elem, method="html", encoding="unicode")
    with open(path, "w") as f:
        f.write(empty_xml)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject