Tuesday, February 27, 2007

NET : Ignore field for XML Serialization

You can ignore certain public field from being serialize if the value for that field
is not specified.

XmlSerializer recognize a specific pattern during serialization to ignore
or include a field into the serialization.

Here are the steps :
1) You create a public field (EG : public int Age).
2) Create a boolean field using the convention PropertyNameSpecified (EG : public boolean AgeSpecified).
3) Apply XmlIgnoreAttribute attribute to the boolean property.

Refer to the following code.

public class Customer
{
public string Name;
public int Age;

[XmlIgnore()]
public bool AgeSpecified;
}


Here is the code to serialize the Customer object. Notice I set the AgeSpecified to false to tell the XmlSerializer not to serialize the Age field.

static void SerializeData()
{
Customer c = new Customer();
c.Name = "Bob";
c.Age = 21;
c.AgeSpecified = false;

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
FileStream fs = new FileStream("simple.xml", FileMode.Create);

// Serialize the object
serializer.Serialize(fs, c);
fs.Close();
}


If you open simple.xml in notepad, you will see that there is no Age field.





Run the following code to deserialize the object from the file.

static void DeserializeData()
{
Customer c = null;

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
FileStream fs = new FileStream("simple.xml", FileMode.Open);

c = (Customer)serializer.Deserialize(fs);
fs.Close();

Console.WriteLine("Age : " + c.Age);
Console.WriteLine("Specified : " + c.AgeSpecified);
}





Now run the serialize and deserialize code again, but this time set the AgeSpecified to true, and below is
the output :





Labels:

1 Comments:

At 12:27 PM, Anonymous Anonymous said...

Thanks, exactly what I needed, not sure where else I'd have found it.

 

Post a Comment

<< Home