How to handle null in xml and c# -2

Let's consider that this was automatically generated xml file and in the second Address tag there is nothing. It is null.

If it was not null , we are going to make a list for address and then continue with a class declaration as below. But if we do so, because of a null address tag it gives us an error.

If possible I would like to add an if statement saying that

if it is null , store it as string. if it is not null , go with the list thing.

Could you please show me in code part how to do that?

Best regards

xml sample:

<?xml version="1.0"?>
<XMLCD>
 <Personnel>
  <AddressDirectory>
    <Owner>Jerry</Owner>
    <Age>29</Age>
    <Company>123</Company>
    <Address>
     <ST>
      <HouseNo>1</HouseNo>
      <StreetName>5th</StreetName>
      <Town>Elmsford</Town>
     </ST>
    </Address>
    <Address> 
    </Address>
  </AddressDirectory>
  <AddressDirectory>
      <Owner>Joe</Owner>
      <Age>24</Age>
      <Company>456</Company>
      <Address>
       <ST>
        <HouseNo>1</HouseNo>
        <StreetName>10Blvd</StreetName>
        <Town>StMichael</Town>
       </ST>
      </Address>
      <Address> 
      </Address>
  </AddressDirectory>
 </Personnel>
</XMLCD>

My code:

        OpenFileDialog ofd = new OpenFileDialog();
        opnFileName = ofd.FileName;

        XmlSerializer deserializer = new XmlSerializer(typeof(XMLCD));
        TextReader reader = new StreamReader(this.opnFileName);
        object obj = deserializer.Deserialize(reader);
        XMLCD XmlData = (XMLCD)obj;
        reader.Close();

    public class XMLCD
    {
         [XmlElement("Personnel")]
         public List<Personnel> PersonnelList = new List<Personnel>();

         public class Personnel
         {
           [XmlElement("AddressDirectory")]
           public List<AddressDirectory> AddressDirectoryList = new List<AddressDirectory>();

           public class AddressDirectory
           {
                 [XmlElement("Owner")]
                 public string Owner{ get; set; }

                 [XmlElement("Age")]
                 public string Age{ get; set; }

                 [XmlElement("Company")]
                 public string Company{ get; set; }


                 [XmlElement("Address")]
                 public List<Address> AddressList = new List<Address>();

                 public class Address
                 {
                       [XmlElement("ST")]
                       public List<ST> STList = new List<ST>();

                       public class ST
                       {
                         [XmlElement("HouseNo")]
                         public string HouseNo{ get; set; }

                         [XmlElement("StreetName")]
                         public string StreetName{ get; set; }

                         [XmlElement("Town")]
                         public string Town{ get; set; }
                }
     }
  }
}

The code above works great only for xml codes who have no null adress tags. When the xml code has null adress tags as shown above it gives an error.

Answers


If you only control de-serializing, you can simply remove unwanted empty Address entries right after deserialization using the Linq .RemoveAll() extension method:

XmlSerializer deserializer = new XmlSerializer(typeof(XMLCD));
XMLCD XmlData;

using (var reader = new StreamReader(this.opnFileName))
{
    XmlData = deserializer.Deserialize(reader) as XMLCD;
}

// loop over all Personnel to cleanse their AddressDirectoryList.AddressList
foreach (Personnel p in XmlData.PersonnelList)
{
    foreach (AddressDirectory ad in p.AddressDirectoryList)
    {
        // RemoveAll predicate checks if ALL properties are null or empty
        ad.AddressList.RemoveAll(a =>
            (string.IsNullOrEmpty(a.HouseNo) &&
             string.IsNullOrEmpty(a.StreetName) &&
             string.IsNullOrEmpty(a.City))
        );
    }
}

Basically the RemoveAll() method just iterates over all items in the AddressList collection.

To simplify the validation you could extend your Address class to validate itself:

public class Address
{
    [XmlElement("HouseNo")]
    public string HouseNo { get; set; }

    [XmlElement("StreetName")]
    public string StreetName{ get; set; }

    [XmlElement("City")]
    public string City{ get; set; }

    [XmlIgnore]
    public bool IsValid
    {
        get
        {
            return !string.IsNullOrEmpty(this.HouseNo)
                && !string.IsNullOrEmpty(this.StreetName)
                && !string.IsNullOrEmpty(this.City);
        }
    }
}

which will allow to use a single condition in your RemoveAll predicate:

ad.AddressList.RemoveAll(a => !a.IsValid);

An non-Linq alternative could be to transform the source Xml using Xslt to filter out empty Address elements.


Need Your Help

A String to int conversion returning 156112 instead of 1 in objective c

objective-c string integer type-conversion

I have a NSMutableDictionary, with values. One of the values is an NSString "1".

ThreadPoolExecutor throws RejectedExecutionException after shutting down

android multithreading threadpoolexecutor

I have two buttons for start download and stop download. I used the ThreadPoolExecutor for multiple downloads. I shut down the ThreadPoolExecutor when the stop button is clicked. And I start execut...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.