Adding an Existing XML File

I have an existing XML file that I would like to add without changing the format. The existing file is as follows:

<Clients>
  <User username="farstucker">
    <UserID>1</UserID>
    <DOB />
    <FirstName>Steve</FirstName>
    <LastName>Lawrence</LastName>
    <Location>NYC</Location>
  </User>
</Clients>

How to add another user to this format? My existing code is:

        string fileLocation = "clients.xml";

        XmlTextWriter writer;

        if (!File.Exists(fileLocation))
        {
            writer = new XmlTextWriter(fileLocation, null);
            writer.WriteStartDocument();

            // Write the Root Element
            writer.WriteStartElement("Clients");

            // End Element and Close
            writer.WriteEndElement();
            writer.Close();
        }
// Append new data here

I thought about using an XmlDocument Fragment to add data, but I'm not sure if I can support the existing format (and empty tags) without messing up the file.

Any advice you could give is greatly appreciated.

EDIT Ive changed the code to read the source XML, but the file continues to be overwritten.

+3
source share
3 answers
+4

- ...

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

, , , System.Xml.Linq.

, .

+1

If you want to use serialization (this means that you have a data object that is required to serialize to XML and add to an existing XML file), you can use this general method SerializeAppend<T>. He does exactly what you need. I also added two more methods for those who can win

public static void Serialize<T>(T obj, string path)
{
    var writer = new XmlSerializer(typeof(T));

    using (var file = new StreamWriter(path))
    {
        writer.Serialize(file, obj);
    }
}


public static T Deserialize<T>(string path)
{
    var reader = new XmlSerializer(typeof(T));
    using (var stream = new StreamReader(path))
    {
        return (T)reader.Deserialize(stream);
    }

}

public static void SerializeAppend<T>(T obj, string path)
{
    var writer = new XmlSerializer(typeof(T));

    FileStream file = File.Open(path, FileMode.Append, FileAccess.Write);

    writer.Serialize(file, obj);

    file.Close();
}
0
source

Source: https://habr.com/ru/post/1741271/


All Articles