是否可以将xml文件分配给struct?
我有xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<Questions>
<Question id="1">
<QuestionText>Question 1?</QuestionText>
<Ans1>Answer</Ans1>
<Ans2>Answer</Ans2>
<Ans3>Answer</Ans3>
<Ans4>Answer</Ans4>
<CorrectAnswer>2</CorrectAnswer>
</Question>
<Question id="2">
<QuestionText>Question 2?</QuestionText>
<Ans1>Answer</Ans1>
<Ans2>Answer</Ans2>
<Ans3>Answer</Ans3>
<Ans4>Answer</Ans4>
<CorrectAnswer>1</CorrectAnswer>
</Question>
</Questions>
和c#代码
public struct Question
{
public string questionText;
public string[] answers;
public int correctAnswerIndex;
public Question(string questionText, string[] answers, int correctAnswerIndex)
{
this.questionText = questionText;
this.answers = answers;
this.correctAnswerIndex = correctAnswerIndex;
}
}
我想用id创建一个新问题foreach xml Question,并分配 问题文本从xml到我的questionText来自struct,struct answers = Ans1,2,3,4,而correctAnswerIndex将是来自xml的正确答案。 我会很感激你的每一个建议。
答案 0 :(得分:4)
您可以使用XML架构定义工具(Xsd.exe)从XML文件自动生成C#类,并使用反序列化将XML中的数据直接读入C#对象
步骤:
使用Xsd.exe
从xml文件生成xsd模式文件xsd Questions.xml /outputdir:C:\myDir
这将生成目录C:\ myDir
下的Questions.xsd使用相同的Xsd.exe从生成的xsd文件生成c#类
xsd Questions.xsd /classes /outputdir:C:\myDir
这将生成目录C:\ myDir
下的Questions.cs使用反序列化从XML读入C#对象
string XmlPath = @"C:\myDir\Questions.xml";
YourQuestionClass qObj = null;
XmlSerializer serializer = new XmlSerializer(typeof(YourQuestionClass));
StreamReader reader = new StreamReader(XmlPath);
qObj = (QuestionClass)serializer.Deserialize(reader);
reader.Close();
答案 1 :(得分:1)
是的,System.Xml.Serialization是你的朋友。但是,如果您的类具有与XML相同的结构,那么它最有效。
using System.Xml.Serialization;
public class Question
{
[XmlElement("QuestionText")]
public string QuestionText {get;set;}
[XmlElement("Answer")]
public string[] Answer {get;set;}
[XmlElement("CorrectAnswer")]
public string CorrectAnswer {get;set;}
}
[XmlRoot("Questions")
public class Questions
{
[XmlElement("Question")]
public Question[] Question {get;set;}
}
或者如果你总是有4个可能的答案你也可以这样
public class Question
{
[XmlElement("QuestionText")]
public string QuestionText {get;set;}
[XmlElement("Ans1")]
public string Answer1 {get;set;}
[XmlElement("Ans2")]
public string Answer2 {get;set;}
[XmlElement("Ans3")]
public string Answer3 {get;set;}
[XmlElement("Ans4")]
public string Answer4 {get;set;}
[XmlElement("CorrectAnswer")]
public string CorrectAnswer {get;set;}
}
[XmlRoot("Questions")
public class Questions
{
[XmlElement("Question")]
public Question[] Question {get;set;}
}
在
之后反序列化很容易Questions questions = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Questions));
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(yourPathToFile);
string xmlString = xmlXrds.OuterXml.ToString();
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
MemoryStream ms = new MemoryStream(buffer);
using (XmlReader reader = XmlReader.Create(ms))
{
questions= (Questions)xmlSerializer.Deserialize(reader);
}
或者你可以马上获得它
StreamReader reader = new StreamReader(yourXmlPath);
questions = (Questions)serializer.Deserialize(reader);
希望有所帮助