Can anyone suggest how to create a c# class to reflect the following example of XML structure please? Basically, the sub-element within the element Value can contain either Integer or String elements.
<Preferences>
<Preference>
<Tag>CY3A</Tag>
<Precedence>XML</Precedence>
<Value>
<Length>4</Length>
<Integer>0</Integer>
</Value>
</Preference>
<Preference>
<Tag>CYRV</Tag>
<Precedence>XML</Precedence>
<Value>
<Length>16</Length>
<String>0000 00 @00000</String>
</Value>
</Preference>
</Preferences>
I have tried to define the class as follows but it didn’t result in what I am looking for. It generates the unwanted d element.
public class ProgrammingConfiguration
{
public int Version { get; set; }
public preferences Preferences { get; set; }
}
public class preferences
{
public preference Preference { get; set; }
}
public class preference
{
public string Tag { get; set; }
public string Precedence { get; set; }
public value Value { get; set; }
}
public class value
{
[XmlElement]
public int Length;
[XmlElement(Type = typeof(Integer)),
XmlElement(Type = typeof(HexBinary))]
public object datafield;
}
public class Integer
{
public string d;
}
public class String
{
public string d;
}
I normally create an xsd and then use the xsd.exe tool to create a .cs class file from the xsd.
xsd.exe is a utility that comes with Visual Studio….
Have a look at http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDFromCls.aspx
But you can do it from the XML too
To solve the string vs integer problem, you can add an xs:choice field to your xsd, this will generate an “Item” which you can then cast as a Int or String as appropriate. Have a look at http://msdn.microsoft.com/en-us/library/exchange/bb426064(v=exchg.140).aspx