【发布时间】:2014-01-22 02:09:34
【问题描述】:
如何使用 XmlReader 读取以下格式的 XML 文件?我已经做了好几天了,但无济于事。当它到达<text> 元素时,读者将其读取为结束元素并忽略该值...不知道为什么...
<?xml version="1.0" encoding="UTF-8"?>
<questions>
<question>
<question_number>1</question_number>
<text>DDDDDFFFFJJJJ</text>
<option>
<id>1</id>
<response>DDDF</response>
</option>
<option>
<id>2</id>
<response>FF</response>
</option>
<option>
<id>3</id>
<response />
</option>
<option>
<id>4</id>
<response />
</option>
</question>
</questions>
我尝试了以下方法,但无济于事:
public bool ImportQuestions(string FileName)
{
try
{
XmlTextReader reader = new XmlTextReader(FileName);
while (reader.Read())
{
if (reader.Name == "question")
{
Question question = new Question();
var subReader = reader.ReadSubtree();
while (subReader.Read())
{
if (subReader.Name == "question_number")
{
question.Id = subReader.ReadElementContentAsInt();
}else if (subReader.Name == "text")
{
question.QuestionText = subReader.ReadElementContentAsString();
} else if (subReader.Name == "option")
{
Option option = new Option();
var ansReader = subReader.ReadSubtree();
while (ansReader.Read())
{
if (ansReader.Name == "id")
{
option.ID = ansReader.ReadElementContentAsString();
}else if (ansReader.Name == "response")
{
option.Response = ansReader.ReadElementContentAsString();
}
}
question.AddToAnswers(option);
}
}
Questions.Add(question);
}
}
reader.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
【问题讨论】:
-
为什么要使用 XmlReader? Linq2Xml 不是更合适吗?
-
我抓取了您的代码并将其粘贴到 LinqPAD 中,它似乎工作正常(我能够毫无问题地打印出“文本”值并继续阅读“选项”子元素。是你确定问题不在其他地方?
-
它在识别
后拾取了一些空文本,然后跳到 并打破此异常“节点类型 EndElement 不支持 ReadElementContentAsString 方法。第 1 行,位置 117。” -
仅供参考,您不应使用
new XmlTextReader()或new XmlTextWriter()。自 .NET 2.0 以来,它们已被弃用。请改用XmlReader.Create()或XmlWriter.Create()。