简体   繁体   中英

Iterating through a list of XML Elements

I would like to place a follow-up to a previously asked question but apparently I'm not allowed to continue this in the same thread.

In my previous question ( Iterating through a list of elements inside an element with a specific index ) I was looking for the value of all of the urls in my xml. But what is the proper way to access different values inside the same node? An example:

<list index="1" name="" title="" id="5702f74a-9df2-12e5-89e0-f947f6dd0a1f">
  <theme>
    <properties>
      <field index="1"/>
      <field index="2" name="title"></field>
    </properties>
    <list>
      <item id="f391fada-90c5-f239-a836-25ca76311286">
         <field index="1">
           <url>49e424a8ae1bf4707bf4d27c4614e905.png</url>
           <title></title>
         </field>
         <field index="2" name="question">This is a question</field>
         <field index="3" name="answer">This is an answer</field>
         <field index="4" name="remark"/>
         <field index="5" name="reveal"/>
       </item>

       <item id="a0b97163-d195-4dce-b970-ecb6eb080403">
         <field index="1">
            <url>49e424a8ae1bf4707bf4d27c4614e905.png</url>
            <title></title>
         </field>
         <field index="2" name="question"/>
         <field index="3" name="answer"></field>
         <field index="4" name="remark"/>
         <field index="5" name="reveal"/>
       </item>
     </list>
  </theme>
</list>

I would like to read this XML piece by piece (item by item in the XML) and store the values of the fields with specific names into variables: So for example:

string url = [value of field URL];
string question= [value of field with name question];
string answer= [value of field with name answer];
string remark= [value of field with name remark];
string reveal= [value of field with name reveal];

Do I have to use for every variable a sortlike query?

var string = xmlDoc.Descendants("list")
    .Where(e => (int)e.Attribute("index") == 1)
    .Descendants("item").Descendants("field")
    .Where(e => (string)e.Attribute("index") == "1")
    .Select(e => (string)e.Value());

Or is there a way to get the fields in a sort of list which I can then search by it's indexnumber?

foreach (field in fields)
{
  switch case (field.name)
  {
    case "question":
      question = field.value;
      break;

    case "answer":
      answer= field.value;
      break;
  }
}

Any ideas are greatly appreciated.

I'd create a helper method to parse the fields into an Item object containing all your properties and use it like this:

var items = from item in doc.Descendants("item")
            let fields = item.Elements("field")             
            select ItemFromFields(fields);

The helper method would switch on the field index, you could implement it like so:

private static Item ItemFromFields(IEnumerable<XElement> fields)
{
    var item = new Item();

    foreach (var field in fields)
    {
        var index = (int)field.Attribute("index");

        switch (index)
        {
            case 1:
                item.Url = (string)field.Element("url");
                break;
            case 2:
                item.Question = field.Value;
                break;
            case 3:
                item.Answer = field.Value;
                break;
            case 4:
                item.Remark = field.Value;
                break;
            case 5:
                item.Reveal = field.Value;
                break;
        }
    }

    return item;
}

For completeness, Item , would look like this:

public class Item
{
    public string Url { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
    public string Remark { get; set; }
    public string Reveal { get; set; }
}

Try this. The URL field doesn't contain a name or index tag so you have to test for name tag not equal null.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = 
                "<list index=\"1\" name=\"\" title=\"\" id=\"5702f74a-9df2-12e5-89e0-f947f6dd0a1f\">\n" +
                   "<theme>\n" +
                     "<properties>\n" +
                       "<field index=\"1\"/>\n" +
                       "<field index=\"2\" name=\"title\"></field>\n" +
                     "</properties>\n" +
                     "<list>\n" +
                       "<item id=\"f391fada-90c5-f239-a836-25ca76311286\">\n" +
                          "<field index=\"1\">\n" +
                            "<url>49e424a8ae1bf4707bf4d27c4614e905.png</url>\n" +
                            "<title></title>\n" +
                          "</field>\n" +
                          "<field index=\"2\" name=\"question\">This is a question</field>\n" +
                          "<field index=\"3\" name=\"answer\">This is an answer</field>\n" +
                          "<field index=\"4\" name=\"remark\"/>\n" +
                          "<field index=\"5\" name=\"reveal\"/>\n" +
                        "</item>\n" +

                        "<item id=\"a0b97163-d195-4dce-b970-ecb6eb080403\">\n" +
                          "<field index=\"1\">\n" +
                             "<url>49e424a8ae1bf4707bf4d27c4614e905.png</url>\n" +
                             "<title></title>\n" +
                          "</field>\n" +
                          "<field index=\"2\" name=\"question\"/>\n" +
                          "<field index=\"3\" name=\"answer\"></field>\n" +
                          "<field index=\"4\" name=\"remark\"/>\n" +
                          "<field index=\"5\" name=\"reveal\"/>\n" +
                        "</item>\n" +
                      "</list>\n" +
                   "</theme>\n" +
                 "</list>\n";

            XDocument doc = XDocument.Parse(input);
            var results = doc.Descendants("item")
                .Select(w => new {
                    url = w.Descendants("url").FirstOrDefault().Value,
                    question = w.Descendants("field").Where(x => x.Attribute("name") != null).Where(y => y.Attribute("name").Value == "question").Select(z => z.Attribute("index").Value).FirstOrDefault(),
                    answer = w.Descendants("field").Where(x => x.Attribute("name") != null).Where(y => y.Attribute("name").Value == "answer").Select(z => z.Attribute("index").Value).FirstOrDefault(),
                    remark = w.Descendants("field").Where(x => x.Attribute("name") != null).Where(y => y.Attribute("name").Value == "remark").Select(z => z.Attribute("index").Value).FirstOrDefault(),
                    reveal = w.Descendants("field").Where(x => x.Attribute("name") != null).Where(y => y.Attribute("name").Value == "reveal").Select(z => z.Attribute("index").Value).FirstOrDefault()
                })
                .ToList();
        }
    }
}
​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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