none
How to Parse XML into a C# object? RRS feed

  • Question

  • I used the XmlWriter to create this string:
    
    <EventInput>
              <Group>12345</Group>
    <Events>
    <Event Id="100" />
    <Event Id="101" />
    <Event Id="102" />
    <Event Id="103" />
    <Event Id="104" />
    </Events>
    </EventInput>

    What would be the simplest way to read and parse this XML string into a C# object (I'm not showing the private members and properties for simplicity)

    class EventInput
    {
    public int group;
            public List<int> EventIds = new List<int>();
    }


    Monday, February 2, 2009 9:01 PM

Answers

  • I believe that in your case XmlSerialization is what you are looking for. Here is how the code would look like for your Xml:

    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
    Pawel
    • Marked as answer by sOltane Tuesday, February 3, 2009 4:29 PM
    Tuesday, February 3, 2009 4:54 AM
    Moderator

All replies

  • I believe that in your case XmlSerialization is what you are looking for. Here is how the code would look like for your Xml:

    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
    Pawel
    • Marked as answer by sOltane Tuesday, February 3, 2009 4:29 PM
    Tuesday, February 3, 2009 4:54 AM
    Moderator
  • I know this question is old, but I stumbled into it and I have a different answer :-)

    The usual way is to generate a class and de-serialize your xml.

    But (warning: shameless self-promotion here) I just published a nuget package, here, with which you don't have to. You just go:

    string xml = System.IO.File.ReadAllText(@"C:\test\books.xml");
    var book = Dandraka.XmlUtilities.XmlSlurper.ParseText(xml);

    That is literally it, nothing else needed. And, most importantly, if your xml changes, your object changes automagically as well.

    If you prefer to download the dll directly, the github page is here.


    Friday, August 23, 2019 6:32 AM