Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am making a WPF that searches through an XML file pulling out restaurant information. The XML is in this format:

    <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>

I want to be able to add a new restaurant to the XML file. I have a textbox for the restaurant name, and type. Then three textboxes for the phone number. 4 comboboxes for the open hour, open minute, close hour, and close minute. I also have 2 listboxes for selecting AM or PM for the open and close times.

I assume I use XmlTextWriter, but I could not figure out how to add the text to a pre-existing XML file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

The simplest way isn't to use XmlTextWriter - it's just to load the whole into an in-memory representation, add the new element, then save. Obviously that's not terribly efficient for large files, but it's really simple if you can get away with it. For example, using 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");

Or, better:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...