Appending an existing XML file

后端 未结 3 2019
一生所求
一生所求 2020-12-11 08:55

I have an existing XML file that I would like to append without changing the format. Existing File looks like this:


  

        
3条回答
  •  失恋的感觉
    2020-12-11 09:35

    You could try something like this...

            string fileLocation = "clients.xml";
    
            if (!File.Exists(fileLocation))
            {
                XmlTextWriter writer = new XmlTextWriter( fileLocation, null );
                writer.WriteStartElement( "Clients" );
                writer.WriteEndElement();
                writer.Close();
            }
    
            // Load existing clients and add new 
            XElement xml = XElement.Load(fileLocation);
                xml.Add(new XElement("User",
                new XAttribute("username", loginName),
                new XElement("DOB", dob),
                new XElement("FirstName", firstName),
                new XElement("LastName", lastName),
                new XElement("Location", location)));
            xml.Save(fileLocation);
    

    That should get you started, just replace the variables with whatever you are using and dont forget to add the System.Xml.Linq namespace.

    If youre still having problems post back here and well help you get through it.

提交回复
热议问题