0

I want to fetch data from XML file and store the values to the C# variables List. So I can use it in different methods also.Below is my XML format:

<fieldmetadata>
<field>
    <name>Object Text</name>
    <datatype>Text</datatype>
    <label>ABC</label>
</field>

<field>
    <name>Object Short Text</name>
    <datatype>String</datatype>
    <label>PQR</label>
</field>

and below is my C# Code:

public List<string> getAllidentifiers()
{     
    List<string> listx = new List<string>();

    XDocument xdoc = XDocument.Load(Path.GetTempPath() + "\\XMLFormat.xml");
    xdoc.Descendants("field").Select(p => new
    {
        name = p.Element("name").Value,
        datatype = p.Element("datatype").Value,
        label = p.Element("label").Value
    }).ToList().ForEach(p =>
    {
        listx.Add(p.name);
        listx.Add(p.datatype);
        listx.Add(p.label);
    });       

   return listx;
}

How can I fetch list elements to variables.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Vivek
  • 103
  • 1
  • 7
  • 1
    So what data do you want to retrieve? In what format? What have you tried?... – Gilad Green Oct 14 '17 at 09:29
  • I want to fetch the xml list data into variables – Vivek Oct 14 '17 at 09:32
  • 1
    It sounds like you should be creating a class to represent a field, with `Name`, `DataType` and `Label` properties - you could then create a `List`. Is that the sort of thing you're looking for? Your question is unclear at the moment. – Jon Skeet Oct 14 '17 at 09:32
  • yes you are right. – Vivek Oct 14 '17 at 09:37
  • But I dont know how to set this values – Vivek Oct 14 '17 at 09:38
  • Set which values? You're already retrieving the three values you want, so which part is confusing you? Do you know how to create your own class, and give it a constructor? – Jon Skeet Oct 14 '17 at 11:04

1 Answers1

1

As your current code just returns a flat list of strings you can achieve it like this:

var result = XDocument.Load("data.xml")
                      .Descendants("field")
                      .SelectMany(f => f.Elements().Select(e => e.Value))
                      .ToList(); 

But I think a better solution would be to return an IEnumerablE<Field>, create the type:

public class Field
{
    public string Name { get; set; }
    public string DataType { get; set; }
    public string Label { get; set; }
}

And deserialize the file like this:

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • I want to store that xml data into List and then fetch there values in variables. – Vivek Oct 14 '17 at 09:43
  • @Angad - the *fetch there values in variables* is not really clear. If you just want a flat string collection then the answer shows it. Otherwise if you want 3 lists, for for each field, then better go with the `Field` class, deserialize the xml and then use linq `.Select` to just retrieve the different properties. – Gilad Green Oct 14 '17 at 11:00