简体   繁体   English

C#获取XML节点值

[英]C# Get XML Node Value

I want to get the question and answer values using C#, but before that I want to get the ID I need. 我想使用C#获取questionanswer值,但在此之前,我想获取所需的ID。 I'm using this XML: 我正在使用以下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# code: C#代码:

XDocument tasks;
int TheIdINeed = 2;
string quest = "";
string answ = "";

On form load: 在表单加载时:

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 = ...)

I'm sorry, my English isn't good. 对不起,我的英语不好。

You could use this 你可以用这个

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;
}

If you need to get the question and answers outside of this scope, I suggest creating a class that will hold the data. 如果您需要获得超出此范围的问题和答案,建议您创建一个可容纳数据的类。 For example, 例如,

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
                    });

You could improve the above by using a Dictionary to store the Question/Answer pair but it's just an example to give you an idea. 您可以通过使用字典来存储问题/答案对来改善上述内容,但这只是一个示例,可以给您一个想法。 in case your QuestionAnswer class is more complicated than just those two properties. 以防您的QuestionAnswer类比这两个属性更复杂。

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"));

you can get all data to dictionary so you won't repeat conversion to string 您可以将所有数据保存到字典中,因此不会重复转换为字符串

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"]

but if there tasks without questions or answers in your xml you have to check if res is contains key before you will get value, or use TryGetValue: 但是,如果您的xml中有没有问题或答案的任务,则必须在获取值之前检查res是否包含键,或者使用TryGetValue:

string question;
res.TryGetValue("question", out question);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM