gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:51:56 25 4
gpt4 key购买 nike

如果找不到,我会创建一个新的 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();

最佳答案

尝试:

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

关于c# - 添加新的 XElement 会在保存时将整个 XML 文件附加到现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9408262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com