Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c# - Adding to XML file

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...