How to serialize to xml return type

chandu king 21 Reputation points
2021-07-06T06:40:02.057+00:00

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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,286 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2021-07-06T08:12:03.137+00:00

    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 );
    
    0 comments No comments

0 additional answers

Sort by: Most helpful