Tuesday, November 4, 2014

When you deserialize a string of XML in C#, try not to make a brittle implementation.

This...

List<FormField> formFields = new List<FormField>();
XDocument xml = XDocument.Parse(responsePacket);
foreach (XElement element in xml.Root.Elements())
{
   if (element.Name == "Fields")
   {
      foreach (XElement formField in element.Elements())
      {
         var xmlReader = XmlReader.Create(new StringReader(formField.ToString()),
               new XmlReaderSettings());
         var serializer = new XmlSerializer(typeof (FormField));
         var deserializedObject = serializer.Deserialize(xmlReader);
         formFields.Add((FormField)deserializedObject);
      }
   }
}

 
 

...for example, is a little bit better than this...

List<FormField> formFields = new List<FormField>();
XDocument xml = XDocument.Parse(responsePacket);
foreach (XElement element in xml.Root.Elements())
{
   if (element.Name == "Fields")
   {
      foreach (XElement formField in element.Elements())
      {
         string name = null;
         string value = null;
         bool? isToTokenize = null;
         foreach (XElement attribute in formField.Elements())
         {
            if (attribute.Name == "Name") name = attribute.Value;
            if (attribute.Name == "Value") value = attribute.Value;
            if (attribute.Name == "IsToTokenize") isToTokenize =
                  Convert.ToBoolean(attribute.Value);
         }
         if (name != null && value != null && isToTokenize != null)
         {
            formFields.Add(new FormField()
            {
               Name = name,
               Value = value,
               IsToTokenize = (bool) isToTokenize
            });
         }
      }
   }
}

 
 

...as in the first example the FormField type may change shape without breaking the implementation.

No comments:

Post a Comment