添加新的XElement会在保存时将整个XML文件附加到现有文件

时间:2012-02-23 06:34:17

标签: c# .net xml windows-phone-7 linq-to-xml

我创建了一个新的xml文档(如果找不到),然后打开它以创建一个新条目。然而,它似乎只是将一个已完成的新XML文件附加到我创建的空白文件的末尾

创建后:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Devices />
添加新的xelement后

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Devices /><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Devices>
  <device>
    <name>blah</name>
    <src00>True</src00>
  </device>
</Devices>

我的代码......我尝试添加两种不同的方式,两者都有相同的结果

           // Create file if not found
            if (!storage.FileExists("settings\\mydevices.xml"))
            {
                using (IsolatedStorageFileStream stream = storage.OpenFile("settings\\mydevices.xml", FileMode.Create, FileAccess.ReadWrite))
                {
                    XDocument devicesDoc =
                        new XDocument(
                            new XDeclaration("1.0", "utf-8", "yes"),
                            new XElement("Devices")
                            );

                    System.IO.StreamWriter file = new System.IO.StreamWriter(stream);
                    devicesDoc.Save(file);
                    file.Dispose();
                }
            }


            // Add new device
            using (IsolatedStorageFileStream stream = storage.OpenFile("settings\\mydevices.xml", FileMode.Open, FileAccess.ReadWrite))
            {

                XDocument mydevicesXml = XDocument.Load(stream);
                //XElement item= new XElement("device",
                //                new XElement("name",selectedDeviceName),
                //                new XElement("src00","True")
                //               );

                //mydevicesXml.Descendants("Devices").First().Add(item);
                //mydevicesXml.Element("Devices").Add(item);

                mydevicesXml.Root.Add(
                    new XElement("device",
                        new XElement("name", selectedDeviceName),
                        new XElement("src00", "True")));


                System.IO.StreamWriter file = new System.IO.StreamWriter(stream);
                mydevicesXml.Save(file);
                file.Dispose();

1 个答案:

答案 0 :(得分:7)

尝试:

XElement root;

if(File.Exists(file))
    root = XElement.Load(file);
else
    root = new XElement("Devices");

root.Add(new XElement("device",
         new XElement("name", selectedDeviceName),
         new XElement("src00", "True")));
root.Save(file);