C#XML - 将对象列表添加到根元素

时间:2016-03-19 19:33:40

标签: c# xml

我对C#的XML API有点问题。我有以下代码将对象列表保存到xml文件中:

public void Export(List<Booking> bookings)
{
    string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "zeitbuchungen.xml");

    XmlDocument xmlDocument = new XmlDocument();
    XPathNavigator xmlNavigator = xmlDocument.CreateNavigator();
    using (XmlWriter xmlWriter = xmlNavigator.AppendChild())
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Booking>), new XmlRootAttribute("Bookings"));
        xmlSerializer.Serialize(xmlWriter, bookings);
    }
    xmlDocument.Save(path);
}

问题是,如果我再次调用此方法,文件 - 当然 - 会被替换,但我想将新列表添加到文件中。

如果我调用该方法两次,这就是文件的样子:

<Bookings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Booking>
    <SerialNumberTerminal>1234567890</SerialNumberTerminal>
    <TransponderID>FBbNAx75KHjN</TransponderID>
    <BookingDateTime>2016-03-19T20:21:01</BookingDateTime>
    <BookingCommand>G</BookingCommand>
  </Booking>
  <Booking>
    <SerialNumberTerminal>1234567890</SerialNumberTerminal>
    <TransponderID>wJAo3EGsuSRI</TransponderID>
    <BookingDateTime>2016-03-19T20:21:01</BookingDateTime>
    <BookingCommand>G</BookingCommand>
  </Booking>
</Bookings>

我已经发现,我可以使用xmlDocument.Load(path)加载现有文件,但我不知道如何将新列表添加到根元素。

1 个答案:

答案 0 :(得分:0)

您必须加载该文件,然后将元素添加到已经执行的操作中。我试着制作这种代码。我希望这会以正确的方式帮助你。 :)

public void Export(List<Booking> bookings)
{
    string path =Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "zeitbuchungen.xml");
    //This block is what you need to add
    XmlDocument doc = new XmlDocument();
    doc.Load(path);
    //////////////////
    using (XmlWriter xmlWriter = xmlNavigator.AppendChild())
    {
        XmlSerializer xmlSerializer =( doc, new XmlRootAttribute("Bookings"));

    using (FileStream fs = new FileStream(path, FileMode.Create))
    {
        xmlSerializer.Serialize(xmlWriter, bookings);
        fs.Close();
    }
    }
    xmlDocument.Save(path);
}