2014-10-28 2 views
0

Мне нужно прочитать строку xml и присвоить значения коллекции списка. Мне нужно прочитать узел вопроса и назначить его переменной списка. Аналогичным образом прочитайте ответ и назначьте его переменной списка. В настоящее время вопрос и ответ перегружаются и не переходят на следующий узел. Может ли кто-нибудь сказать мне, в чем проблема?Чтение строки xml и списка заполняющих списков

Ниже приведен код

XmlDocument xmlDocument = new XmlDocument(); 

      var fataQuestionnaire = @"<?xml version=""1.0"" encoding=""UTF-16""?> 
          <FatcaQuestionnaire xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> 
          <QuestionAnswers> 
            <QuestionAnswer> 
            <Question>What is your source of wealth?</Question> 
            <Answer>I am italian </Answer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>What is your occupation and name of employer?</Question> 
            <Answer>Bestinvest</Answer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>Do you have a business or residence in?</Question> 
            <Answer>Yes</Answer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>How long have you lived outside of Albania</Question> 
            <Answer>5 years</Answer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>Do you return to Albania on a regular basis</Question> 
            <Answer>Yes</Answer> 
            <SubQuestionAnswer> 
             <Question>How frequently?</Question> 
             <Answer>every year</Answer> 
            </SubQuestionAnswer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>Do you have family in Albania?</Question> 
            <Answer>Yes</Answer> 
            <SubQuestionAnswer> 
             <Question>Family relationship?</Question> 
             <Answer>My parents lives there</Answer> 
            </SubQuestionAnswer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>Are you connected to the government of Albania?</Question> 
            <Answer>Yes</Answer> 
            <SubQuestionAnswer> 
             <Question>Nature of association</Question> 
              <Answer>I was an ex minister</Answer> 
            </SubQuestionAnswer> 
            </QuestionAnswer> 
            <QuestionAnswer> 
            <Question>Do you send or receive money from Albania?</Question> 
            <Answer>Yes</Answer> 
            <SubQuestionAnswer> 
             <Question>How often and why?</Question> 
             <Answer>Every month for my parents to live with.</Answer> 
            </SubQuestionAnswer> 
            </QuestionAnswer> 
          </QuestionAnswers> 
          </FatcaQuestionnaire>"; 

      XmlTextReader reader = new XmlTextReader(new StringReader(fataQuestionnaire)); 


      xmlDocument.Load(reader); 

      XmlElement xmlRoot = xmlDocument.DocumentElement; 
      if (xmlRoot != null) 
      { 
       XmlNodeList xnlNodes = xmlRoot.SelectNodes("/FatcaQuestionnaire/QuestionAnswers/QuestionAnswer"); 
       List<string> questionanswer = new List<string>(); 

      if (xnlNodes != null) 
       foreach (XmlNode xndNode in xnlNodes) 
       { 
        if (xndNode["Question"] != null) 
         questionanswer[0] = xndNode["Question"].InnerText; 

        if (xndNode["Answer"] != null) 
         questionanswer[1] = xndNode["Answer"].InnerText; 

        if (xndNode["Question"] != null) 
         questionanswer[2] = xndNode["Question"].InnerText; 

        if (xndNode["Answer"] != null) 
         questionanswer[3] = xndNode["Answer"].InnerText; 
       } 

       } 
      } 
+0

Вы образец не имеет особого смысла - вы пытаетесь установить значения для несуществующих элементов ' List' (например, 'questionanswer [2] = ...') - пожалуйста, убедитесь, что код по крайней мере похож на тот, который может работать. Также рассмотрите отладку, чтобы предоставить более подробную информацию. –

ответ

0

Заменить:

foreach (XmlNode xndNode in xnlNodes) 
{ 
    if (xndNode["Question"] != null) 
    questionanswer[0] = xndNode["Question"].InnerText; 

    if (xndNode["Answer"] != null) 
    questionanswer[1] = xndNode["Answer"].InnerText; 

    if (xndNode["Question"] != null) 
    questionanswer[2] = xndNode["Question"].InnerText; 

    if (xndNode["Answer"] != null) 
    questionanswer[3] = xndNode["Answer"].InnerText; 
} 

с

foreach (XmlNode xndNode in xnlNodes) 
{ 
    if (xndNode["Question"] != null) 
    questionanswer.Add(xndNode["Question"].InnerText) 

    if (xndNode["Answer"] != null) 
    questionanswer.Add(xndNode["Answer"].InnerText); 
} 

Вам нужно добавить в список.

0

Когда вы впервые создали Список, он был пуст, и поэтому у него не было объектов для добавления. Вы пытаетесь установить значения в несуществующие поля в массиве.

Итак: изменить код из этого:

foreach (XmlNode xndNode in xnlNodes) 
{ 
    if (xndNode["Question"] != null) 
    questionanswer[0] = xndNode["Question"].InnerText; 

    if (xndNode["Answer"] != null) 
    questionanswer[1] = xndNode["Answer"].InnerText; 

    if (xndNode["Question"] != null) 
    questionanswer[2] = xndNode["Question"].InnerText; 

    if (xndNode["Answer"] != null) 
    questionanswer[3] = xndNode["Answer"].InnerText; 
} 

Для этого:

foreach (XmlNode xndNode in xnlNodes) 
{ 
    if (xndNode["Question"] != null) 
    questionanswer.Add(xndNode["Question"].InnerText); 

    if (xndNode["Answer"] != null) 
    questionanswer.Add(xndNode["Answer"].InnerText); 

} 
Смежные вопросы