Ganesh Rajan Ganesh Rajan - 3 months ago 9
C# Question

Deserializing XML to C# Objects

Consider this XML document

<contacts>
<contact>
<id>1</id>
<type>Multiple</type>
<address>
<value>IND</value>
</address>
<address>
<value>CHINA</value>
</address>
<address>
<value>PAK</value>
</address>
</contact>
<contact>
<id>1</id>
<type>Single</type>
<address>
<id>1</id>
<name>XYZ</name>
<country>IND</country>
</address>
</contact>
</contacts>


I want to convert this xml to c# object. For that i have created the below classes.

[XmlRoot("address")]
public class MultipleAddress
{
[XmlElement("value")]
prop string value { get; set; }
}

[XmlRoot("address")]
public class SingleAddress
{
[XmlElement("name")]
prop string name { get; set; }
[XmlElement("country")]
prop string country { get; set; }
}


public class BaseContact
{
prop int id { get; set; }
prop string type { get; set; }
}

public class MultipleContact: BaseContact
{
prop MultipleAddress[] address { get; set; }
}

public class SingleContact: BaseContact
{
prop SingleAddress address { get; set; }
}

// Main Class
public calss Contact
{
[XmlElement("contact")]
public <???> contact { get; set; }
}


If i replace "???" with BaseContact, the address property will be omitted. Is there any way that i can use to successfully deserialize the xml to an object without missing any values.

Answer

Which of the three substrings do you want?

p0-\[[^\]]+\]

Will match your first, as seen here.

Your second substring would be matched by this :

p1-\[[^\]]+\]\]

As seen here.

With this, you should easily be able to create the regex for your third substring, an exercise you should try!