python to_xml to display xsi:nil="" instead of nothing

I have this export script of a dataframe in xml format:

df.to_xml('df.xml',root_name='dataroot',row_name='Anexa_1I',
          namespaces={"xsd": "http://www.w3.org/2001/XMLSchema",
                      "xsi": "http://www.w3.org/2001/XMLSchema-instance"},
          prefix="",xml_declaration=False,index = False,pretty_print = True);

what I get for null values is:

<data_grafic/\>

and what I want is:

 <data_grafic
 xsi:nil="true" /\>

I tried using the parameter na_rep but that creates a string and I want to to indicate that an element is intentionally empty or null

Upvotes: 0

Views: 36

Answers (1)

You may need to post process your XML for the specific fields where you expect a NULL.

data = {
    "id": [1, 2, 3],
    "data_grafic": [np.nan, "value", None]
}

df = pd.DataFrame(data)

xml_str = df.to_xml(
    root_name="dataroot",
    row_name="Anexa_1I",
    namespaces={"xsd": "http://www.w3.org/2001/XMLSchema",
                "xsi": "http://www.w3.org/2001/XMLSchema-instance"},
    prefix="",
    xml_declaration=False,
    index=False,
    pretty_print=True,
    na_rep="NULL"
)
xml_str = xml_str.replace("<data_grafic>NULL</data_grafic>", "<data_grafic xsi:nil=\"true\" /\>")
print(xml_str)
<dataroot xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Anexa_1I>
    <id>1</id>
    <data_grafic xsi:nil="true" /\>
  </Anexa_1I>
  <Anexa_1I>
    <id>2</id>
    <data_grafic>value</data_grafic>
  </Anexa_1I>
  <Anexa_1I>
    <id>3</id>
    <data_grafic xsi:nil="true" /\>
  </Anexa_1I>
</dataroot>

Upvotes: 0

Related Questions