Pandas to_xml() 设置 xsi 值

时间:2021-07-08 08:02:24

标签: python pandas xml xslt

我正在尝试输出到 XML 以符合定义的标准格式,因此我无法更改它。我当前的代码:

import pandas as pd

inp = {
    'EmployeeId': [1, 2, 3, 4, 5],
    'Name': ['ABC', 'DEF', 'HJK', 'LMN', 'OPQ']
}

df = pd.DataFrame(inp)

print(df)

namespaces = {
    '': "",
    'xsi': "http://www.w3.org/2001/XMLSchema-instance",
    'xsd': "http://www.w3.org/2001/XMLSchema"
}

df['type'] = 'EmployeeDto'

df.to_xml('Test.xml',
          index=False,
          row_name='anyType',
          root_name='ArrayOfAnyType',
          namespaces=namespaces,
          encoding='utf-16',
          attr_cols=['type'],
          elem_cols=['EmployeeId', 'Name'])

给我这个:

<?xml version='1.0' encoding='utf-16'?>

<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="">
  <anyType type="EmployeeDto">
    <EmployeeId>1</EmployeeId>
    <Name>ABC</Name>
  </anyType>
  <anyType type="EmployeeDto">
    <EmployeeId>2</EmployeeId>
    <Name>DEF</Name>
  </anyType>
  <anyType type="EmployeeDto">
    <EmployeeId>3</EmployeeId>
    <Name>HJK</Name>
  </anyType>
  <anyType type="EmployeeDto">
    <EmployeeId>4</EmployeeId>
    <Name>LMN</Name>
  </anyType>
  <anyType type="EmployeeDto">
    <EmployeeId>5</EmployeeId>
    <Name>OPQ</Name>
  </anyType>
</ArrayOfAnyType>

这与我设法获得的差不多。我需要使用 xsi: 标记让它看起来像这样,而且我似乎无法在没有 "":"" 的情况下添加命名空间,这会给我一个空白的 xmlns 值...

<?xml version="1.0" encoding="utf-16"?>

<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <anyType xsi:type="EmployeeDto">
        <EmployeeId>114354</EmployeeId>
        <Name>Patrick</Name>
    </anyType>
    <anyType xsi:type="EmployeeDto">
        <EmployeeId>114362</EmployeeId>
        <Name>Raymond</Name>
    </anyType>
    <anyType xsi:type="BEmployeeDto">
        <EmployeeId>114364</EmployeeId>
        <Name>Paul</Name>
    </anyType>
</ArrayOfAnyType>

0 个答案:

没有答案