2012-08-22 70 views
0

我有一个ListView有一堆东西。无论在第17个位置总是会中断(ObjectDisposedException“无法从关闭的TextReader读取”)。 1至16以及18至24工作正常。如果我从17日到16日移动x,它会再次运行,但是新的17日会休息。我的代码并没有专指任何地方。C#XMLReader奇怪的第17个位置关闭XMLReader错误

该XML文件的格式为

<Profiles> 
    <Profile name="a" type="A"> 
    <ListOne>1,2,3,4,5,6,7,8</ListOne> 
    <ListTwo>1,2,3,4,5,6,7,8</ListTwo> 
    </Profile> 
    <Profile name="b" type="B"> 
    ... 
    ... 
</Profiles> 

的代码很简单。我一定要找到我感兴趣的配置文件,并返回其作为一个子

string CurrentProfile = ""; 
using (StreamReader SR = new StreamReader(MyXMLFilePath)) 
{ 
    XmlTextReader TR = new XmlTextReader(SR); 
    do 
    { 
    TR.ReadToFollowing("Profile"); 
    TR.MoveToFirstAttribute(); 
    CurrentName = TR.Value; 
    TR.MoveToNextAttribute(); 
    string CurrentType = TR.Value; 

    if (CurrentName == MyName && CurrentType == MyType) 
    { 
     TR.MoveToElement(); 
     XmlReader subtree = TR.ReadSubtree(); 
     return subtree; 
    } 
    } 
    while (CurrentName != ""); 
} 

一个方法,然后我有一个从树翻出名单1和2的方法。

if(subtree != null) 
{ 
    subtree.ReadToFollowing("ListOne"); 
    subtree.Read(); 
    string[] ListOneArray = subtree.Value.Split(','); 

    subtree.ReadToFollowing("ListTwo"); 
    subtree.Read(); 
    string[] ListTwoArray = subtree.Value.Split(','); 
} 

这就是问题发生的地方。 ObjectDisposedException无法从关闭的TextReader读取。当我到达子树时,它总是会中断.ReadToFollowing(“ListTwo”),但仅当我在XML列表中选择第17个配置文件时才会中断。我没有看到我在任何时候关闭文本阅读器。此外,这适用于配置文件18,19,20等,以及1到16,但不管怎么样,总是会在17位中断。我看不出第17个地方与其他地方有什么不同。

请帮忙!

回答

1

ReadSubTree()返回仍然从基础流读取的阅读器。
由于您在阅读该阅读器之前关闭了该流,因此它不起作用。

一般来说,XmlReader的向前模型相当烦人。
除非你处理非常大的文件,否则应该使用LINQ to XML来代替;它使用起来更容易。

+0

好的,我会研究一下。你能看到大多数配置文件始终如此工作的原因,但从来没有为其中的一个配置文件工作? – xwiz

0

我个人觉得用Linq2Xml有个XML

XDocument xDoc = XDocument.Load(...); 
var profiles = xDoc.Descendants("Profile") 
    .Where(x=>x.Attribute("name").Value=="a") 
    .Select(p => new 
    { 
     List1 = p.Element("ListOne").Value.Split(','), 
     List2 = p.Element("ListTwo").Value.Split(',') 
    }) 
    .ToList();