3

I'm using this:

public void WriteSettings(string key, string value)
{
    XmlWriterSettings xmlSettings = new XmlWriterSettings();
    xmlSettings.Indent = true;
    xmlSettings.NewLineOnAttributes = true;

    XmlWriter writer = XmlWriter.Create(TMP_FULLPATH, xmlSettings);
    writer.WriteStartElement("settings");
    writer.WriteAttributeString(key, value);
    writer.WriteEndAttribute();
    writer.WriteEndDocument();
    writer.Flush();
    writer.Close();
}

But any modification replaces all attributes with only the last remaining attribute that I am trying to add. For example:

current XML:

<?xml version="1.0" encoding="utf-8"?>
<settings TitleFormat="name:%name% date:%date%" />

when I do:

WriteSettings("foo", "baa"); 

the XML is:

<?xml version="1.0" encoding="utf-8"?>
<settings foo="baa" />

instead of:

<?xml version="1.0" encoding="utf-8"?>
<settings TitleFormat="name:%name% date:%date%" foo="baa" />

How can I fix that?

2 Answers 2

1

You are writing a new file, with no consideration at all of the old. To update a document, you must load it into a DOM, edit the DOM, and save the DOM:

var doc = new XmlDocument();
doc.Load(path);
doc.DocumentElement.SetAttribute(key, value);
doc.Save(path);
Sign up to request clarification or add additional context in comments.

Comments

1

you are creating new file each time you call XmlWriter.Create(), do something like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.