gpt4 book ai didi

python - 使用 lxml 将行添加到 xml

转载 作者:行者123 更新时间:2023-12-01 06:10:33 25 4
gpt4 key购买 nike

我有一个方法可以保存保留,但每次创建 XmlReportGenerator 的新实例时都会覆盖输出文件

from lxml import etree
from Flights.FlightTravelReservation import FlightTravelReservation

class XmlReportGenerator:
root = None
doc = None

def __init__(self):
self.root = etree.Element('results')
self.doc = etree.ElementTree(self.root)

def add_flight_row(self, flight_travel_reservation):
page_element = etree.SubElement(self.root, 'FlightTravel')
etree.SubElement(page_element, 'QuantityOfPassengers').text =
str(len(flight_travel_reservation.paxes))
etree.SubElement(page_element,'Id').text =
flight_travel_reservation.reservation_id

def Save(self, path = 'Flights.xml'):
outFile = open(path, 'wb')
self.doc.write(outFile)

示例输出为:

<results>
<FlightTravel>
<Paxes>4</Paxes>
<Id>259183</Id>
</FlightTravel>
</results>

如何修改 add_flight_row 方法以添加新行?例如,我想要这样的东西:

<results>
<FlightTravel>
<Paxes>4</Paxes>
<Id>259183</Id>
</FlightTravel>
<FlightTravel>
<Paxes>9</Paxes>
<Id>123456</Id>
</FlightTravel>
</results>

我添加了测试方法:

def test_test(self,a,b):

page_element = etree.SubElement(self.root,'FlightTravel')

etree.SubElement(page_element,'QuantityOfPassengers').text = a
etree.SubElement(page_element,'Id').text = b

return page_element

这就是我使用它的方式:

x=XmlReportGenerator()
x.test_test("a","b")
x.Save("test.xml")

x=XmlReportGenerator()
x.test_test("c","d")
x.Save("test.xml")

结果我有:

<results>
<FlightTravel>
<Flights/>
<QuantityOfPassengers>c</QuantityOfPassengers>
<Id>d</Id>
</FlightTravel>
</results>

而不是

<results>
<FlightTravel>
<Flights/>
<QuantityOfPassengers>a</QuantityOfPassengers>
<Id>b</Id>
</FlightTravel>
<FlightTravel>
<Flights/>
<QuantityOfPassengers>c</QuantityOfPassengers>
<Id>d</Id>
</FlightTravel>
</results>

最佳答案

您需要为 XmlReportGenerator 定义一个 Load 函数来加载旧结果。

class XmlReportGenerator(object):
def __init__(self):
# __init__, add_flight_row, and Save

def load(self, path='Flights.xml'):
try:
self.doc = etree.ElementTree()
self.root = self.doc.parse(path)
except IOError:
pass

并像这样使用它:

# day 1
x=XmlReportGenerator()
x.load('test.xml') # Silently catches the error if the file does not exit yet
x.test_test("a","b")
x.Save('test.xml')

# day2
x=XmlReportGenerator()
x.load('test.xml')
x.test_test("c","d")
x.Save("test.xml")

关于python - 使用 lxml 将行添加到 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6174765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com