在Python中创建嵌套的XML文档

时间:2018-06-26 21:25:24

标签: python xml csv transform elementtree

我偶尔访问过这个论坛,但到目前为止,它已经使我走了很长一段路,但我一直陷于困境以寻求帮助。我正在尝试从CSV结构创建XML文档,目的是要准备一些看起来像这样的东西:

ID,Type,Currency,Notional,Underlying,Maturity Date,Representation Type
ID1,COMMIT,EUR,100,,2018-06-01,Bond
ID2,COMMIT,AUD,110,,2018-03-25,Stock

并将其转换为如下形式。

<tradeRequests>     
<tradeRequest>
    <id>ID1</id>
    <newDeals size="1">
        <deal>
            <id>ID1</id>
            <terms>
                <id>ID1</id>
                <MaturityDate>2018-06-01</MaturityDate>                 
            </terms>
        </deal>
    </newDeals>     
</tradeRequest>
<tradeRequest>
    <id>ID2</id>
    <newDeals size="1">
        <deal>
            <id>ID2</id>
            <terms>
                <id>ID2</id>
                <MaturityDate>2018-06-01</MaturityDate>                 
            </terms>
        </deal>
    </newDeals>     
    </tradeRequest> 
</tradeRequests>

问题在于我的脚本似乎没有以正确的方式格式化项目,因为每一行本质上应该是一个tradeRequest,但我看不到这种格式。

这是我的代码段,它将从大量列中提取列的子集。

import csv
import xml.etree.ElementTree as ET
import xml.dom.minidom

tradeRequests = ET.Element("tradeRequests")
tradeRequest = ET.SubElement(tradeRequests, "tradeRequest")
newDeals = ET.SubElement(tradeRequest, "newDeals")
deal = ET.SubElement(newDeals, "deal")
dealid = ET.SubElement(deal, "id")

with open('TestCase.csv') as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        ET.SubElement(tradeRequest, "id").text = row['ID']
        ET.SubElement(tradeRequest, "newDeals", {'size':"1"} )
        ET.SubElement(dealid, "id").text = row['ID']
        ET.SubElement(dealid, "maturityDate").text = row['Maturity Date']
        tree = ET.ElementTree(tradeRequests)
        tree.write("Testcase.xml" )

xml = xml.dom.minidom.parse('Testcase.xml')
pretty_xml_as_string = xml.toprettyxml()

print pretty_xml_as_string

问题是我似乎无法正确嵌套项目。我尝试创建父/子组合,但未成功。相反,基于该代码,我看到的输出看起来像这样。

<tradeRequests>
    <tradeRequest>
        <newDeals>
            <deal>
                <id>
                    <id>ID1</id>
                    <maturityDate>2018-06-01</maturityDate>
                    <id>ID2</id>
                    <maturityDate>2018-03-25</maturityDate>
                </id>
            </deal>
        </newDeals>
        <id>ID1</id>
        <newDeals size="1"/>
        <id>ID2</id>
        <newDeals size="1"/>
    </tradeRequest>
</tradeRequests>

任何帮助一如既往。

我没想到需要动态循环并创建元素的这种情况

ID1,COMMIT,EUR,100,,2018-06-01,Bond
ID2,110,2018-03-25,Stock
ID2,110,2018-03-26,A
ID2,110,2018-03-26,B
ID2,110,2018-03-26,C

实际上,我需要创建一个将遍历ID2的元素,并根据有多少行来动态创建一个新元素,这是未知的。

所以我的预期结果将是

<tradeRequests>
    <ids>
    <id>ID1</id>
            <element>
                <maturityDate>2018-06-01</maturityDate>
                <type>Stock</type
            <element>
        </id>
        <id>ID2</id>
            <element>
                <maturityDate>2018-03-25</maturityDate>
                <type>A</type>
            </element>
            <element>
                <maturityDate>2018-03-25</maturityDate>
                <type>B</type>
            </element>
                <maturityDate>2018-03-25</maturityDate>
                <type>C</type>
            </element>
        </id>
</tradeRequests>

1 个答案:

答案 0 :(得分:1)

我强烈建议您使用出色的lxml library.,因为它是基于C库libxml2的包装器,并且它包含元素生成器对象E,这确实使您的工作非常容易,它确实非常快:

import csv
import lxml.etree
from lxml.builder import E

with open('TestCase.csv') as csvfile:
    results = E.tradeRequests(*(
        E.tradeRequest(
            E.id(row['ID']),
            E.newDeals(
                E.deal(
                    E.id(row['ID']),
                    E.terms(
                        E.id(row['ID']),
                        E.MaturityDate(row['Maturity Date']),
                    )
                ),
                size="1",
            )
        ) for row in csv.DictReader(csvfile))
    )

print(lxml.etree.tostring(results, pretty_print=True))

结果:

<tradeRequests>
  <tradeRequest>
    <id>ID1</id>
    <newDeals size="1">
      <deal>
        <id>ID1</id>
        <terms>
          <id>ID1</id>
          <MaturityDate>2018-06-01</MaturityDate>
        </terms>
      </deal>
    </newDeals>
  </tradeRequest>
  <tradeRequest>
    <id>ID2</id>
    <newDeals size="1">
      <deal>
        <id>ID2</id>
        <terms>
          <id>ID2</id>
          <MaturityDate>2018-03-25</MaturityDate>
        </terms>
      </deal>
    </newDeals>
  </tradeRequest>
</tradeRequests>