C# 将子元素添加到XDocument中的根元素
我正在尝试使用XDocument.Load向XML文件中的根元素添加一个节点。问题是,当我添加一个新节点时,它会重新重复标题。 以下是创建XML文件的函数:C# 将子元素添加到XDocument中的根元素,c#,xml,linq,windows-phone-8,C#,Xml,Linq,Windows Phone 8,我正在尝试使用XDocument.Load向XML文件中的根元素添加一个节点。问题是,当我添加一个新节点时,它会重新重复标题。 以下是创建XML文件的函数: private void createDoc() { XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Items", new XComment("H
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>
下面是调用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>
测试
测试1
6.
0
这与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);
}
最好的解决方案是重新打开流。不要重新定位,文件稍后收缩时会出现其他问题
大致上,请注意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);
}
这个问题与此代码的Xml部分完全无关!您正在使用同一个流来读写文件,因此加载xml后,文件光标位于文件的末尾。 此修复方法在调用doc.Save方法之前,请尝试使用isoStream.SetLength(0)或isoStream.Seek(0,SeekOrigin.Begin)(如果新文件小于原始文件,则后一个选项可能会留下不需要的文本)
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);
}