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 have an existing XML file that I would like to append without changing the format. Existing File looks like this:

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

How can I add another user using 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

Ive thought about using XmlDocument Fragment to append the data but Im not certain if I can maintain the existing format ( and empty tags ) without messing up the file.

Any advice you could give is much appreciated.

EDIT Ive changed the code to read the original XML but the file keeps getting overwritten.

See Question&Answers more detail:os

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

1 Answer

You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don't worry, it won't mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the PreserveWhitespace property (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).


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