2012-08-22 45 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();