使用lxml将行添加到xml

时间:2011-05-30 09:54:20

标签: python lxml

我有一个方法可以保存,但每次创建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>

2 个答案:

答案 0 :(得分:2)

您需要为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")

答案 1 :(得分:0)

只需在您要添加的每一行的同一实例上重复调用add_flight_row(或test_test):

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