Adding new XElement appends entire XML file to exi

2019-07-16 09:29发布

问题:

I am created a new xml document if one isn't found, then opening it to create a new entry. However it just seems to be appending a completed new XML file to end of the blank file I created

after creation:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Devices />

after adding new 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>

my code ... I've tried adding two different ways, both with the same results

           // 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:

Try:

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