0

I have an xml file that looks like this

<Root>
  <Element1>17890</Element>
  <Element2>0001</Element2>
  <Element3>123451324A</Element3>
  <Element4>1</Element4>
  <Element5>ABC</Element5>
  <Element6>DEF</Element6>
  <Element7>99.10</Element7>
  <Element8>GHI</Element8>
  <Element9>2014-01-25</Element9>
  <Element10>JKL</Element10>
  <Element11>737268</Element11>
</Root>

And I have a corresponding class that have all the element names as properties. Let's say I have a collection of all the elements such as

IEnumerable<XElement> elements;

How do I set the property values of the class to the element values from the xml file?

The only thing I have thought of is to loop over elements and make a big switch statement with sections such as

...
case "Element3":
    model.Element3 = element.Value;
    break;
...

Is there a better solution?

Spennet
  • 15
  • 4

1 Answers1

0

Assuming you already have a class Model with the fields you want to get from the xml:

var elements = XDocument.Load("XMLFile1.xml").Root.Elements();
var model = new Model()
{
    Element1 = elements.FirstOrDefault(t => t.Name.LocalName == "Element1"),
    Element2 = elements.FirstOrDefault(t => t.Name.LocalName == "Element2"),
};

Another option is to create a dictionary, so you don't need to update your model every time a new tag name is added to the xml file.

var model = new Dictionary<string, string>();
foreach(XElement tag in elements)
{
   model[tag.Name.LocalName] = tag.Value;
}

Or using Linq

var model = elements.ToDictionary(e => e.Name.LocalName, e => e.Value);

Finally you can generate a dynamic object directly from the xml. There's an example here: Deserialize XML To Object using Dynamic

Community
  • 1
  • 1
derloopkat
  • 6,232
  • 16
  • 38
  • 45