如何使用panda的to_xml和多个根名称?

2024-09-28 05:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用to_xml编写xml,如下所示:-

df.to_xml(
    os.path.join(file_path, f"{os.path.basename(file)}"),
    index=False,
    root_name="GenevaLoader",
    namespaces=namespaces,
    row_name="Expenses_New",
    xml_declaration=False,
)

我明白了:

<GenevaLoader xmlns:GenevaLoader="blahh" xmlns:xsi="blahh" xmlns="" >
<Expenses_New>
<Comments>AAA</Comments>
<Portfolio>BBB</Portfolio>
<NetCounterAmount>1</NetCounterAmount>
</Expenses_New>
<Expenses_New>
<Comments>AAA</Comments>
<Portfolio>XXX</Portfolio>
<NetCounterAmount>2</NetCounterAmount>
</Expenses_New>
<Expenses_New>
<Comments>CCC</Comments>
<Portfolio>ZZZ</Portfolio>
<NetCounterAmount>3</NetCounterAmount>
</Expenses_New>
</GenevaLoader>

基本上,我想在所有的新标签周围添加一个TransactionRecord标签,这是我的行名,但下面是我的根名root\u name='GenevaLoader'

<GenevaLoader xmlns:GenevaLoader="blahh" xmlns:xsi="blahh"  xmlns="">
<TransactionRecords>
<Expenses_New>
<Comments>AAA</Comments>
<Portfolio>BBB</Portfolio>
<NetCounterAmount>1</NetCounterAmount>
</Expenses_New>
<Expenses_New>
<Comments>AAA</Comments>
<Portfolio>XXX</Portfolio>
<NetCounterAmount>2</NetCounterAmount>
</Expenses_New>
<Expenses_New>
<Comments>CCC</Comments>
<Portfolio>ZZZ</Portfolio>
<NetCounterAmount>3</NetCounterAmount>
</Expenses_New>
</TransactionRecords>
</GenevaLoader>

Tags: topathnamenewosxmlcommentsfile
1条回答
网友
1楼 · 发布于 2024-09-28 05:21:57

正如@HenryEcker在评论中提到的,操作xml的最佳方法是使用xml解析器:

from lxml import etree
load = """your output xml above"""
doc = etree.XML(load.encode())

#this is one way of approaching the namespaces issue:
targets = doc.xpath('//*[local-name()="Expenses_New"]')
etree.SubElement(doc, 'TransactionRecords')
destination = doc.xpath('//*[local-name()="TransactionRecords"]')[0]
for target in targets:
    destination.append(target)
destination.tail = "  \n"
print(etree.tostring(doc).decode())

输出:

<GenevaLoader xmlns:GenevaLoader="blahh" xmlns:xsi="blahh">
   <TransactionRecords><Expenses_New>
      <Comments>AAA</Comments>
      <Portfolio>BBB</Portfolio>
      <NetCounterAmount>1</NetCounterAmount>
   </Expenses_New>
   <Expenses_New>
      <Comments>AAA</Comments>
      <Portfolio>XXX</Portfolio>
      <NetCounterAmount>2</NetCounterAmount>
   </Expenses_New>
   <Expenses_New>
      <Comments>CCC</Comments>
      <Portfolio>ZZZ</Portfolio>
      <NetCounterAmount>3</NetCounterAmount>
   </Expenses_New>
</TransactionRecords>  
</GenevaLoader>

相关问题 更多 >

    热门问题