1

I am getting XML from sql server and i am able to deserialize it with proper Human class.

public class Human
{
public string name {get;set;}
}

after giving value for name property i want to serialize it with different root name, because i want to deserialize it again with new class name

public class Boy
{ 
public string name {get;set;}
}

please give a solution

  • 4
    "please give a solution"? That's not how StackOverflow works. Please show us what you tried, and why that didn't work first. What errors are you getting, what result are you expecting and what is the actual result at the moment? It's much easier to help if we know what problems you are facing. – Patrick May 01 '16 at 09:50
  • You need three classes : Human, Boy, and name. You can use the same name class in both Boy and Human. – jdweng May 01 '16 at 10:12

1 Answers1

3

You can change the root element name, pass in the serializer the XmlRootAttribute parameter.

var human = new Human { name = "Smit" };

var xs = new XmlSerializer(typeof(Human), new XmlRootAttribute("Boy"));

using (var fs = new FileStream("test.xml", FileMode.Create))
    xs.Serialize(fs, human);
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
  • 3
    If you construct an `XmlSerializer` using an `XmlRootAttribute`, you must cache the serializer for reuse later, or else you will have a severe resource leak. See [the documentation](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) and also [XmlSerializer Performance Issue when Specifying XmlRootAttribute](https://stackoverflow.com/questions/1534810) or [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145). – dbc May 01 '16 at 16:58