如何在不替换所有属性的情况下编写xml属性?

时间:2011-12-29 13:05:56

标签: c# .net xml

我正在使用它:

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

但是,任何修改都只用我尝试添加的最后一个剩余属性替换所有属性。例如:

当前XML:

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

当我这样做时:

WriteSettings("foo", "baa"); 

XML是:

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

而不是:

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

我该如何解决?

2 个答案:

答案 0 :(得分:1)

每次拨打XmlWriter.Create()时都会创建新文件,执行this之类的操作。

答案 1 :(得分:1)

你正在写一个新文件,完全不考虑旧文件。要更新文档,您必须将其加载到DOM中,编辑DOM并保存DOM:

var doc = new XmlDocument();
doc.Load(path);
doc.DocumentElement.SetAttribute(key, value);
doc.Save(path);