[英]XMLReader misrepresenting element in xml file
如何使用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;
}
我已經好幾天了,但無濟於事。
讓我使用LINQ to XML
更容易,只需添加兩個類Question
和Option
如下所示:
public class Question
{
public int Number { get; set; }
public string Text { get; set; }
public List<Option> Options { get; set; }
}
public class Option
{
public int Id { get; set; }
public string Response { get; set; }
}
然后使用LINQ to XML
:
XDocument xDoc = XDocument.Load("filepath");
var questions = xDoc.Descendants("question").Select(q => new Question
{
Number = (int) q.Element("question_number"),
Text = (string) q.Element("text"),
Options = (from op in q.Elements("option")
select new Option
{
Id = (int) op.Element("id"),
Response = (string) op.Element("response")
}).ToList()
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.