question

chanduking-3255 avatar image
0 Votes"
chanduking-3255 asked Viorel-1 answered

How to serialize to xml return type

Hello Everyone,

I have below models and i need the return xml response like below. Here how to do this. please help me

 public class School
     {        
         public List<Student> StudentList;        
         public int SchoolID { get; set; }       
         public string  SchoolName { get; set; }
     }
 public class Student
 { 
   public string StudentName { get; set; }
   public string ClassName { get; set; }
   public int ? Age { get; set; }          
 }

Required Output

 <RESPONSE>
     <School>
         <SchoolID>102</SchoolID>
         <SchoolName>ABC</SchoolName>
         <StudentList>
             <Student>
                 <StudentName>JOHN</StudentName>
                 <ClassName>IX</ClassName>
                 <Age>13</Age>
             </Student>
             <Student>
                 <StudentName>Taylor</StudentName>
                 <ClassName>IIX</ClassName>
                 <Age>11</Age>
             </Student>
         </StudentList>
     </School>
     <School>
         <SchoolID>103</SchoolID>
         <SchoolName>BCD</SchoolName>
         <StudentList>
             <Student>
                 <StudentName>CHRIS</StudentName>
                 <ClassName>IV</ClassName>
                 <Age>9</Age>
             </Student>
             <Student>
             </StudentList>
         </School>
     </RESPONSE>


Thanks,
King


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

Try something like this:

 List<School> myschools = . . . the list of the schools
    
 var xr = new XmlSerializer( typeof( List<School> ), new XmlRootAttribute { ElementName = "RESPONSE" } );
    
 string xml;
    
 using( var sw = new StringWriter( ) )
 {
     xr.Serialize( sw, myschools );
    
     xml = sw.ToString( );
 }
    
 // display the result
 Console.WriteLine( xml );


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.