概述
在开发metro应用操作xml文件时遇到如题所示的异常,不知道是原本的Bug怎么的,不明白
async Task<XmlDocument> AddChildNode()
{
try
{
Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data");
Windows.Storage.StorageFile xmlFile = await storageFolder.GetFileAsync("checkResults.xml");
Windows.Data.Xml.Dom.XmlDocument doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(xmlFile);
List<Dictionary<string, string>> checkResults = new List<Dictionary<string, string>>();
Dictionary<string, string> checkResult = null;
XmlNodeList nodeLists = doc.GetElementsByTagName("CheckResult");
foreach(IXmlNode node in nodeLists)//到第二次循环就会抛出Collection was modified; enumeration operation may not execute的异常
{
XmlNodeList tmp = node.ChildNodes;
for (int j = 0; j < tmp.Count; j++)
{
checkResult = new Dictionary<string, string>();
//不知道在metro里面为什么会多出这么个字节点,所以就如下屏蔽掉了
if (tmp[j].NodeName != "#text")
{
checkResult.Add(tmp[j].NodeName, tmp[j].InnerText);
}
}
IXmlNode newNode = doc.CreateElement("checkPeople");
newNode.InnerText = "tony";
node.AppendChild(newNode);
checkResults.Add(checkResult);
}
await doc.SaveToFileAsync(xmlFile);
return doc;
}
catch(Exception e)
{
string strError = e.Message;
return null;
}
}
具体原因,还没搞明白,
解决办法就是用for循环代替foreach
async Task<XmlDocument> AddChildNode()
{
try
{
Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data");
Windows.Storage.StorageFile xmlFile = await storageFolder.GetFileAsync("checkResults.xml");
Windows.Data.Xml.Dom.XmlDocument doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(xmlFile);
List<Dictionary<string, string>> checkResults = new List<Dictionary<string, string>>();
Dictionary<string, string> checkResult = null;
XmlNodeList nodeLists = doc.GetElementsByTagName("CheckResult");
//代替foreach
for (int i = 0; i < nodeLists.Length; i++){
XmlNodeList tmp = nodeLists[i].ChildNodes;
for (int j = 0; j < tmp.Count; j++)
{
checkResult = new Dictionary<string, string>();
if (tmp[j].NodeName != "#text")
{
checkResult.Add(tmp[j].NodeName, tmp[j].InnerText);
}
}
IXmlNode newNode = doc.CreateElement("checkPeople");
newNode.InnerText = "tony";
nodeLists[i].AppendChild(newNode);
checkResults.Add(checkResult);
}
await doc.SaveToFileAsync(xmlFile);
return doc;
}
catch(Exception e)
{
string strError = e.Message;
return null;
}
}
最后
以上就是贪玩硬币为你收集整理的metro 异常 Collection was modified; enumeration operation may not execute的全部内容,希望文章能够帮你解决metro 异常 Collection was modified; enumeration operation may not execute所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复