读取和检索xml元素

时间:2014-10-29 12:47:23

标签: c# xml

我需要读取xml文件中的所有嵌套元素。以下是该计划。在下面的程序中,我能够获得问题和答案的值,但不能获得SubQuestionAnswer / Question和SubQuestionAnswer / Answer。有人能告诉我程序中有什么问题

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");
                string questionanswer =string.Empty;


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

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


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

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


            }

2 个答案:

答案 0 :(得分:1)

索引器不支持XPath语法。你可以这样修理它:

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

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

答案 1 :(得分:1)

另一种选择:使用XDocument和Linq。而不是XmlDocument。

加载xml:

XDocument doc = XDocument.Parse(fataQuestionnaire);

使用示例:

List<KeyValuePair<string,string>> allQuestionAnswers = doc.Descendants("QuestionAnswer").Union(doc.Descendants("SubQuestionAnswer"))
    .Select(qa=>new KeyValuePair<string,string>(qa.Element("Question").Value, qa.Element("Answer").Value)).ToList();

foreach (var pair in allQuestionAnswers)
{
    Console.WriteLine("Q: " + pair.Key +"\nA: " + pair.Value + "\n");
}

结果:

Q: What is your occupation and name of employer?
A: Bestinvest

Q: Do you have a business or residence in?
A: Yes

Q: How long have you lived outside of Albania
A: 5 years

Q: Do you return to Albania on a regular basis
A: Yes

Q: Do you have family in Albania?
A: Yes

Q: Are you connected to the government of Albania?
A: Yes

Q: Do you send or receive money from Albania?
A: Yes

Q: How frequently?
A: every year

Q: Family relationship?
A: My parents lives there

Q: Nature of association
A: I was an ex minister

Q: How often and why?
A: Every month for my parents to live with.

或:

doc.Descendants("QuestionAnswer").ToList().ForEach(qa =>
{
    Console.WriteLine("Q: " + qa.Element("Question").Value + "\nA: " + qa.Element("Answer").Value);
    var sqa = qa.Element("SubQuestionAnswer");
    if (sqa != null)
    {
        Console.WriteLine("\tQ: " + sqa.Element("Question").Value + "\n\tA: " + sqa.Element("Answer").Value);
    }
    Console.WriteLine();
 });

结果:

Q: What is your source of wealth?
A: I am italian 

Q: What is your occupation and name of employer?
A: Bestinvest

Q: Do you have a business or residence in?
A: Yes

Q: How long have you lived outside of Albania
A: 5 years

Q: Do you return to Albania on a regular basis
A: Yes
    Q: How frequently?
    A: every year

Q: Do you have family in Albania?
A: Yes
    Q: Family relationship?
    A: My parents lives there

Q: Are you connected to the government of Albania?
A: Yes
    Q: Nature of association
    A: I was an ex minister

Q: Do you send or receive money from Albania?
A: Yes
    Q: How often and why?
    A: Every month for my parents to live with.