0

This is my first time I am using so maybe I have silly question. I would like to parse two types of objects from XML. First one is a simple:

<MyObjects>
   <MyObjectType1>
    <id>1</id>
    <name>EasyObject1</name>
    <param1>1.05</param1>
    <param2>1.25</param2>
   </MyObjectType1>
 </MyObjects>

And I am using following function for parsing:

private ObjectsModel LoadObjects4File(XDocument xdoc)
    {
        ObjectsModel loadedModels = new ObjectsModel();
        //************************
        var data = from query in xdoc.Descendants("MyObjectType1")
            select new MyObjectType1Model
                   {
                       ID = (int)query.Element("id"),
                       Name = (string)query.Element("name"),
                       Param1= (float)query.Element("param1"),
                       Param2= (float)query.Element("param2")
                   };

        for (int i = 0; i<data.ToList().Count; i++)
        {
         loadedModels .AddExistingPropeller(data.ElementAt(i));
        }
     return loadedModels ;
    }

Now I would like to do something similar for more comlicated/complex XML that holds information about a object that is composed from properties and also from objects with their own parameters. The XML looks like this:

<Project>
    <id>1</id> 
    <name>Project 1</name>
    <dateCreated>1.1.2014</dateCreated>
    <dateModified>2.1.2014</dateModified>
    <Statistic>
        <param1>123</param1>
            <param2>123</param2>
    </Statistic>
    <Measurements>
      <Measurement>
        <id>1</id>
        <name>Measurement 1</name>
        <param1>10,10,5,5</param2>
        <param2>1</param2>
        <ObjectProperty1>
            <id>1</id>
            <name>Eq 1</name>
            <param1>1.05</param1>
            <param2>1.25</param#2>
        </ObjectProperty1>

.....

I think I need to do recursive scan of the XDocument a build the final Project object piece by piece, but I am bit stuck on this. Does anyone has an idea how to do this? Any idea will be appritiated...

  • 1
    There are tools that can be used to generate class files from XML files. [Generate C# class from XML](http://stackoverflow.com/q/4203540/390278). Use it. On a side note, it is a terrible idea to embed positional information in the name your XML elements (i.e., param1, param2, etc.). That makes processing the document harder than necessary. If you need that info, make it an attribute of the element. – Jeff Mercado Apr 02 '14 at 23:00
  • 1
    you should look at this tutorial : [Convert XML to Object using LINQ](http://www.codeproject.com/Tips/366993/Convert-XML-to-Object-using-LINQ) – Gabriel GM Apr 02 '14 at 23:53
  • Re: Gabriel GM - this was exacly what I was looking for, Thanks a lot!!! – user2835433 Apr 03 '14 at 08:49

0 Answers0