0
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
    <question>Which country's flag is this?</question>
    <img src="North_Korea.jpg"></img>
    <option value="Norway"></option>
    <option value="Philippines"></option>
    <option value="North Korea" isRight="true"></option>
    <option value="South Korea"></option>
    <option value="North_Korea.jpg"></option>
 </item>
 </root>

Above is the xml file. i want to fetch all the element's attributes values. But not able to fetch element's attributes value as it is repeated. I used below code

  XDocument xdoc = XDocument.Load("Assets/xml_files/flags.xml");                    

        foreach (var item in xdoc.Descendants("item").Elements())
        {
            switch (item.Name.LocalName)
            {
                case "img":
                    questions.ImageName = item.Attribute("src").Value;
                    break;
                case "option":                       
                    questions.OptionA = item.Attribute("value").Value;
                    questions.OptionB = item.Attribute("value").Value;
                    questions.OptionC = item.Attribute("value").Value;
                    questions.OptionD = item.Attribute("value").Value;
                    break;
                case "desc":
                    questions.Description = item.Value;
                    break;
            }
        }     

using above code i am getting output as
optionA=Norway optionB=Norway optionC=Norway optionD=Norway Instead there must be different values as in xml file. Please help me out. Thanks for your time.

4

1 回答 1

0

将您的代码更改为:

var i = 0;

var lstOptions = new List<string>();

XDocument xdoc = XDocument.Load("Assets/xml_files/flags.xml");                    

        foreach (var item in xdoc.Descendants("item").Elements())
        {
            switch (item.Name.LocalName)
            {
                case "img":
                    questions.ImageName = item.Attribute("src").Value;
                    break;
                case "option":           
                    lstOption.add(item.Attribute("value").Value);
                    break;
                case "desc":
                    questions.Description = item.Value;
                    break;
            }
        } 

        questions.OptionA = lstOption[0];
        questions.OptionB = lstOption[1];
        questions.OptionC = lstOption[2];
        questions.OptionD = lstOption[3];
于 2013-05-12T09:39:41.407 回答