我希望使用C#获取question
和answer
值,但在此之前我想获得我需要的ID。我正在使用这个XML:
<root>
<information>
<name>Tasks</name>
<date>15-05-2005</date>
</information>
<tasks>
<task>
<id>1</id>
<question>Here comes question 1</question>
<answer>Answer 1</answer>
</task>
<task>
<id>2</id>
<question>Here comes question 2</question>
<answer>Answer 2</answer>
</task>
<task>
<id>3</id>
<question>Here comes question 3</question>
<answer>Answer 3</answer>
</task>
</root>
C#代码:
XDocument tasks;
int TheIdINeed = 2;
string quest = "";
string answ = "";
表单加载:
tasks = XDocument.Load(leveltoload);
var status = tasks.Element("level").Element("information");
quest = tasks.Element("root").Element("tasks").Element("task").Element("question").Value; // It returns me the first task data, but I need to load data with required Id (int TheIdINeed = ...)
对不起,我的英语不好。
答案 0 :(得分:3)
你可以用这个
string id = "2";
var qa = doc.Descendants("tasks").Elements("task")
.Where(x => x.Element("id").Value == id).FirstOrDefault();
if (qa != null)
{
var question = qa.Element("question").Value;
var answer = qa.Element("answer").Value;
}
如果你需要在这个范围之外得到问题和答案,我建议创建一个保存数据的类。例如,
public class QuestionAnswer
{
public string ID { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
}
var qa = doc.Descendants("tasks").Elements("task")
.Where(x => x.Element("id").Value == id)
.Select(x => new QuestionAnswer()
{
ID = "2",
Question = x.Element("question").Value,
Answer = x.Element("answer").Value
});
您可以通过使用词典存储问题/答案对来改进上述内容,但这只是一个给您一个想法的示例。如果您的QuestionAnswer类比这两个属性更复杂。
答案 1 :(得分:2)
var empty = new XElement("e");
var sID = id.ToString();
var element = tasks.Descendants("task")
.FirstOrDefault(x => ((string)x.Element("id")) == sID);
string quest = (string)((element ?? empty).Element("question"));
string answ = (string)((element ?? empty).Element("answer"));
答案 2 :(得分:1)
您可以将所有数据都添加到字典中,这样您就不会重复转换为字符串
var res = tasks.Descendants("task")
.Select(x => x.Elements().ToDictionary(e => e.Name.ToString(), e => (string)e.Value))
.FirstOrDefault(x => x["id"] == id);
res["question"]
res["answer"]
但是如果您的xml中没有任何问题或答案的任务,您必须先检查res是否包含密钥才能获得值,或者使用TryGetValue:
string question;
res.TryGetValue("question", out question);