我正在尝试使用 XDocument.Load 将节点添加到 XML 文件中的根元素。问题是当我添加新节点时它会重复 header 。 这是创建 XML 文件的函数:
private void createDoc()
{
XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Items", new XComment("Here will be added new nodes")));
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists("positions2.xml"))
{
Debug.WriteLine("File Exists!!!");
isoStore.DeleteFile("positions.xml");
}
else
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("positions2.xml", FileMode.Create, isoStore))
{
doc.Save(isoStream);
}
}
}
}
从这里看来一切都很好并且输出也正常:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Here will be added new nodes-->
</Items>
要将子节点添加到根节点,我使用此函数:
private void AppendToXMLFile(string reg, string butname, int oldposition, int newposition)
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("positions2.xml", FileMode.Open, isoStore))
{
XDocument doc = XDocument.Load(isoStream);
var newElement = new XElement("channel",
new XElement("region", reg),
new XElement("name", butname),
new XElement("oldposition", oldposition),
new XElement("newpostions", newposition));
doc.Element("Items").Add(newElement); //add node to root node
doc.Save(isoStream, SaveOptions.OmitDuplicateNamespaces);
}
}
}
这是调用 AppendToXMLFile
函数后的输出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Here will be added new nodes-->
</Items><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Comment to prevent <Items />-->
<channel>
<region>test</region>
<name>test1</name>
<oldposition>6</oldposition>
<newpostions>0</newpostions>
</channel>
</Items>
最佳答案
这与 XDocument 操作无关(它们没问题),但您将新文件附加到旧文件。
问题的相关部分:
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("positions2.xml", FileMode.Open, isoStore))
{
// A: read it and leave Strean.Position at the end
XDocument doc = XDocument.Load(isoStream);
... // add Elements
// B: write the new contents from the last Position (behind the original)
doc.Save(isoStream, SaveOptions.OmitDuplicateNamespaces);
}
最好的解决方案是重新打开 Stream。不要重新定位,稍后文件缩小时会遇到其他问题。
粗略地记下 FileMode 值:
XDocument doc;
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("positions2.xml", FileMode.Read, isoStore))
{
doc = XDocument.Load(isoStream);
}
... // add Elements
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("positions2.xml", FileMode.Create, isoStore))
{
doc.Save(isoStream, SaveOptions.OmitDuplicateNamespaces);
}
关于c# - 将子项添加到 XDocument 中的根 XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26800403/