我有一个ListView,有很多东西。无论第17个点中的任何内容总是中断(ObjectDisposedException“无法从已关闭的TextReader中读取”)。 1到16以及18到24的工作正常。如果我将x从第17位移到第16位,它将再次起作用,但新的第17次打破。我的代码没有特别提到任何地方。
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中读取。当我到达subtree时,它总是会中断.ReadToFollowing(“ListTwo”),但前提是我在XML列表中选择了第17个配置文件。我不知道我在任何时候关闭文本阅读器。此外,这适用于配置文件18,19,20等以及1到16,但无论如何总是在17位处断开。我不知道第17个位置与其他位置有什么不同。
请帮忙!
答案 0 :(得分:1)
ReadSubTree()
返回仍然从基础流中读取的读者
由于您在从该阅读器读取之前关闭了流,因此无法正常工作。
一般来说,XmlReader的仅向前模型使用起来很烦人 除非你处理非常大的文件,否则你应该使用LINQ to XML;它更容易使用。
答案 1 :(得分:0)
我个人觉得在使用xmls
时更容易使用Linq2XmlXDocument 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();
答案 2 :(得分:0)
你在哪里关闭subtree
?根据MSDN文档,只是想知道最佳做法是否可以在代码中的某处显式关闭subtree
XmlReader。
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree.aspx