问题描述
我有一种方法可以将 XML 加载到 XDocument 并修改其元素然后保存.但是当我重新加载它时.我收到此错误:
I have a method which load XML to a XDocument and modify its elements then save.But when I reload it. I got this error :
意外的 XML 声明.XML 声明必须是文档中的第一个节点,并且不允许在它之前出现空格字符.
我检查了 XML,发现 XDocument 没有保存更改的内容,而是创建了一个副本并保存.
I checking the XML and see that the XDocument didn't save the changed but create a duplicate and save.
它像这个示例xml一样保存旧的和新的:
It save the old one and the new one like this example xml :
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>Unknown</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>1.0.0.0</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
这里是我用来修改和保存 XML 的代码:
Here the code I used to modify and save XML :
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.ReadWrite))
{
//var xdoc = XDocument.Load("APPSDATA.xml");
var xdoc = XDocument.Load(stream, LoadOptions.None);
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
xdoc.Save(stream);
}
我该如何解决这个问题?
How can I solve this problem ?
推荐答案
看起来您正在将修改后的文档附加到当前文件内容的末尾.这就是为什么你以后不能再次解析它.
Looks like you're appending modified document at the end of current file content. That's why you can't parse it later again.
我会将 read 和 write 部分分成不同的 using
语句:
I would split read and write parts into different using
statements:
XDocument xdoc;
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.Read))
{
xdoc = XDocument.Load(stream, LoadOptions.None);
}
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Truncate, FileAccess.Write))
{
xdoc.Save(stream);
}
在第二个 using
语句上设置 FileMode.Truncate
将清除以前的文件内容,应该如何解决您的问题.
Setting FileMode.Truncate
on second using
statement will clear previous file content, what should fix your problem.
这篇关于XDocument 写入重复的 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!