Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

Parse and transform XML string into list of objects using C#?

I have the following XML string:

<rows>
  <row>
    <id>
      <old>2125</old>
    </id>
    <name>
      <old>test</old>
    </name>
    <amount>
      <old>62</old>
    </amount>
  </row>
</rows>

Can Linq be used to transform the above into a list of the following class:

public class Row
{
    public int Id;
    public string Fields;
}

where Fields will contain the above row in this format:

id|2125^name|text^amount|62

Upvotes: 0

Views: 1215

Answers (3)

MikeT
MikeT

Reputation: 5500

Linq itself wont do it but if you use an XMLDocument or some other XML interpreter to parse the XML into an object collection then your can use linq to read the collection

https://msdn.microsoft.com/en-us/library/system.xml.xmldocument%28v=vs.110%29.aspx

so

var rows = from d in xmlDoc.ChildNodes
           where d.Name = "row"
           select new {id= d.Attributes.FirstOrDefault(a=>a.Name=="id"),Other=d.Attributes.Where(a=>a.Name!="id");

Upvotes: 0

scartag
scartag

Reputation: 17680

Using linq to XML and a bit of foreach loop, you could try as below.

    var str = @"<rows>
  <row>
    <id>
      <old>2125</old>
    </id>
    <name>
      <old>test</old>
    </name>
    <amount>
      <old>62</old>
    </amount>
  </row>
</rows>";

 var elements = XElement.Parse(str);

 var rows = elements.Elements("row");

  var list = new List<Row>();

  foreach(var row in rows)
  {
     var id = Int32.Parse(row.Element("id").Element("old").Value);

     var name = row.Element("name").Element("old").Value;

     var amount = row.Element("amount").Element("old").Value;

     var fields = string.Format("id|{0}^name|{1}^amount|{2}",id, name, amount);

     list.Add(new Row { Id = id, Fields = fields});
  }


}

Upvotes: 1

Dave
Dave

Reputation: 987

I believe that in your case XmlSerialization is what you are looking for. Below is an examlpe :

namespace consoleApp {  

    [XmlRoot()]  
    public class EventInput {  

        private string group;  

        public string Group {  
            get { return group; }  
            set { group = value; }  
        }  

        private Event[] events;  

        public Event[] Events {  
            get { return events; }  
            set { events = value; }  
        }          
    }  

    public class Event {  
        private int id;  

        [XmlAttribute]  
        public int Id {  
            get { return id; }  
            set { id = value; }  
        }  
    }  



    class Program {  

        public static void Main() {  

            string xml = @"  
                <EventInput> 
                    <Group>12345</Group> 
                    <Events> 
                        <Event Id=""100"" /> 
                        <Event Id=""101"" /> 
                        <Event Id=""102"" /> 
                        <Event Id=""103"" /> 
                        <Event Id=""104"" /> 
                        </Events> 
                </EventInput>";  

            XmlSerializer serializer = new XmlSerializer(typeof(EventInput));  
            EventInput ei = (EventInput)serializer.Deserialize(new StringReader(xml));  

            Console.WriteLine(ei.Group);  
            foreach(Event e in ei.Events) {  
                Console.WriteLine(e.Id);  
            }  

            Console.WriteLine("\n=============================\n");  

            ei = new EventInput() {  
                Group = "1111",  
                Events = new Event[] {   
                    new Event() { Id = 3},   
                    new Event() { Id = 7},   
                    new Event() { Id = 10}}  
            };  

            serializer.Serialize(Console.Out, ei);  
        }  
    }  
}

In case of more complicated xml documents - if you have schema - you can use xsd.exe to auto-generate the class hierarchy for you. For more details about XmlSerialization attributes take a look here: http://msdn.microsoft.com/en-us/library/83y7df3e(VS.85).aspx

Hope this helps

Upvotes: 1

Related Questions