Reputation: 433
I have one class Person and it has some public properties . Now I want to serialize person class but with some selected properties only. This can be achieve by making that property private but I don't want to change any property as private.
If its not possible using serialisation then, what is another way to create xml doc for object with selected properties only.
Note: All properties must be public.
class Program
{
static void Main(string[] args)
{
Person person = new Person();
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer xmlSerializer = new XmlSerializer(person.GetType());
xmlSerializer.Serialize(memoryStream, person);
using (FileStream fileStream = File.Create("C://Output.xml"))
{
memoryStream.WriteTo(fileStream);
fileStream.Close();
}
memoryStream.Close();
}
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
public Person()
{
Id = 1;
Name = "Sam";
Salary = 50000.00;
}
}
Current Output
<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>1</Id>
<Name>Sam</Name>
<Salary>50000</Salary>
</Person>
Expected Output
<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Salary>50000</Salary>
</Person>
Upvotes: 0
Views: 1308
Reputation: 11731
can you give a try to below code and just use XmlIgnore attribute on he properties which you not require :-
[XmlIgnore]
public int Id { get; set; }
[XmlIgnore]
public string Name { get; set; }
public double Salary { get; set; }
Upvotes: 0