C# streamreader读取xml文件,然后file.move移动xml文件-c
使用Jon Skeet的代码C# streamreader读取xml文件,然后file.move移动xml文件-c,c#,C#,使用Jon Skeet的代码 static IEnumerable<XElement> SimpleStreamAxis(string inputUrl, string elementName) { using (XmlReader reader = XmlReader.Create(inputUrl)) { reader.MoveToContent(); while
static IEnumerable<XElement> SimpleStreamAxis(string inputUrl,
string elementName)
{
using (XmlReader reader = XmlReader.Create(inputUrl))
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == elementName)
{
XElement el = XNode.ReadFrom(reader) as XElement;
if (el != null)
{
yield return el;
}
}
}
}
}
}
编辑:
看起来using streamreader中的成品率没有关闭文件。有人能证实这一点吗?如果您可以使用纯Linq到Xml解决方案,您可以:
static IEnumerable<XElement> SimpleStreamAxis(string filePathAndName, string elementName)
{
XDocument doc = XDocument.Load(filePathAndName);
IEnumerable<XElement> results = from n in doc.Descendants(elementName)
select n;
//Do more stuff with the results as needed...
doc.Save(filePathAndName); //Note you can change the location by supplying a different path
return results;
}
在退出using块之前,您是否尝试过显式关闭读卡器 更新 当您使用yield时,它实际上不会做任何事情,直到您枚举IEnumerable。这就是为什么您在文件保持打开状态时遇到问题的原因 见本问题:
您可能需要创建IEnumerable,填充它,关闭流,然后返回IEnumerable。使用should invoke Dispose,哪个应该关闭流…您是否尝试过纯Linq到Xml的解决方案,或者您的Xml文件太大而无法使用DOM方法?您应该发布您自己问题的答案,这样它就不会一直以未回答的形式出现在头版。@Scott,我没有资格回答自己的问题?我以前回答过自己的问题。你发现了什么地方错了,只要你把它写下来作为一个答案,那么是的:-这也阻止了其他人打开帖子,阅读所有内容,只是为了发现你解决了问题的一部分。
static IEnumerable<XElement> SimpleStreamAxis(string filePathAndName, string elementName)
{
XDocument doc = XDocument.Load(filePathAndName);
IEnumerable<XElement> results = from n in doc.Descendants(elementName)
select n;
//Do more stuff with the results as needed...
doc.Save(filePathAndName); //Note you can change the location by supplying a different path
return results;
}