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
416 views
in Technique[技术] by (71.8m points)

c# - Appending an existing XML file

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

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

1 Reply

0 votes
by (71.8m points)

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


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

...