我会使用XmlWriter而不是每次都覆盖文件并在现有树之后写入数据。
XmlWriterSettings reglages = new XmlWriterSettings();
reglages.Indent = true;
using (XmlWriter writer = XmlWriter.Create("historique.xml", reglages))
{
writer.WriteStartDocument();
// ...
writer.WriteEndDocument();
}
编辑:我的XmlDocument解决方案(不是XDocument)
XmlDocument DocXml = new XmlDocument();
XmlNode body;
if (File.Exists("file.xml"))
{
DocXml.Load("file.xml");
body = DocXml.SelectSingleNode("body");
}
else
{
XmlDeclaration xmlDeclaration = DocXml.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = DocXml.DocumentElement;
DocXml.InsertBefore(xmlDeclaration, root);
body = DocXml.CreateElement("body");
DocXml.AppendChild(body);
}
XmlNode ele1 = DocXml.CreateElement("ele1 ");
body.AppendChild( ele1 );
XmlNode ele2 = DocXml.CreateElement("ele2");
ele2.InnerText = "Text ele2";
ele1.AppendChild(ele2);
DocXml.Save("file.xml");
首次使用(文件创建):
<?xml version="1.0" encoding="UTF-8"?>
<body>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
</body>
其他用途(文件修改):
<?xml version="1.0" encoding="UTF-8"?>
<body>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
<ele1>
<ele2>Text ele2</ele2>
</ele1>
</body>
答案 0 :(得分:0)
我不确定你为什么要这样做;但是,您可以创建一个文件流,然后将文件流提供给XmlWriter.Create的重载http://msdn.microsoft.com/en-us/library/x972ksd0.aspx
我没有IDE,但是我的头脑看起来像这样:
using(FileStream s = new FileStream("file.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (XmlWriter writer = XmlWriter.Create(s))
{
writer.WriteStartDocument();
// ...
writer.WriteEndDocument();
}