2013-08-11 2 views
2

questionanswer 값을 C#을 사용하여 가져오고 싶지만 그 전에 필요한 ID를 얻고 싶습니다. 나는이 XML을 사용하고 있습니다 :C# 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

완벽한 영어 당신은 항상 나에게 분을 구입 이길 – Savage

답변

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 클래스가 두 속성보다 복잡하다면

+0

.... –

+1

이것은 약간 비효율적이다 술어를 취하는 tOrDefualt 오버로드입니다. –

+0

예, 작동합니다! 고맙습니다! – mirelana

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

'XElement.Empty'와 같은 것은 존재하지 않습니다 (IsEmpty를 의미하지 않는다면 정적 속성은 아닙니다). – keyboardP

+1

@ 키 보드 P 수정 됨. –

1

당신이 입술 있는지 확인해야하는 XML에 질문 또는 답변이없는 작업이 키가 포함되어 있으면 문자열

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

로 변환을 반복하지만하지 않습니다 있도록 사전에 모든 데이터를 얻을 수 있습니다 당신이 가치를 얻을, 또는 사용하기 전에 TryGetValue : 당신은 전나무를 사용할 수 있기 때문에

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