添加到XML文件

时间:2012-03-18 19:08:13

标签: c# xml wpf text

我正在制作一个WPF,搜索XML文件,提取餐馆信息。 XML采用以下格式:

    <FoodPhoneNumbers>
      <Restaurant Name="Pizza Place">
        <Type>Pizza</Type>
        <PhoneNumber>(123)-456-7890</PhoneNumber>
        <Hours>
          <Open>11:00am</Open>
          <Close>11:00pm</Close>
        </Hours>
      </Restaurant>
    </FoodPhoneNumbers>

我希望能够在XML文件中添加新餐馆。我有一个餐馆名称和类型的文本框。然后是三个文本框的电话号码。 4个组合框用于开放时间,开放时间,关闭时间和关闭时间。我还有2个列表框,用于在开放和关闭时间选择AM或PM。

我假设我使用XmlTextWriter,但我无法弄清楚如何将文本添加到预先存在的XML文件中。

2 个答案:

答案 0 :(得分:10)

最简单的方法是不使用XmlTextWriter - 它只是将整个加载到内存中表示,添加新元素,然后保存。显然,对于大型文件来说这并不是非常有效,但是如果你可以侥幸逃脱它,那真的很简单。例如,使用XDocument

XDocument doc = XDocument.Load("test.xml");
XElement restaurant = new XElement("Restaurant",
    new XAttribute("Name", "Frenchies"),
    new XElement("Type", "French"),
    new XElement("PhoneNumber", "555-12345678"),
    new XElement("Hours",
         new XElement("Open", "1:00pm"),
         new XElement("Close", "2:00pm")));
doc.Root.Add(restaurant);
doc.Save("test.xml");

或者,更好:

XDocument doc = XDocument.Load("test.xml");
Restaurant restaurant = ...; // Populate a Restaurant object

// The Restaurant class could know how to serialize itself to an XElement
XElement element = restaurant.ToXElement();  

doc.Root.Add(element);

答案 1 :(得分:2)

XmlSerializer类的实例可用于实现此目的。

[XmlRoot("FoodPhoneNumbers")]
public class FoodPhoneNumbers
{
    [XmlElement(ElementName = "Restaurant")]
    public List<Restaurant> Restaurants { get; set; }
}

public class Restaurant
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlElement]
    public string Type { get; set; }

    [XmlElement]
    public string PhoneNumber { get; set; }

    [XmlElement(ElementName = "Hours")]
    public List<Hours> Hours { get; set; }
}

public class Hours
{
    [XmlElement]
    public string Open { get; set; }

    [XmlElement]
    public string Close { get; set; }
}

序列化/反序列化代码:

// Deserialize.
FoodPhoneNumbers food;
using (Stream inputStream = File.OpenRead(inputFilePath))
    food = (FoodPhoneNumbers) xmlSerializer.Deserialize(inputStream);

// Add a new one.
Restaurant restaurant = new Restaurant
    {
        Name = "Coffee restraurant",
        PhoneNumber = "0xFF",
        Type = "Coffee shop"
    };
food.Restaurants.Add(restaurant);

// Serialize.
using (Stream outputStream = File.OpenWrite(outputFilePath))
    xmlSerializer.Serialize(outputStream, food);