IPAddress does not have a default constructor and cannot be serialized normally. IPAddrss supports the following constructor types:
1: public IPAddress(byte[] address);
2: public IPAddress(long newAddress);
3: public IPAddress(byte[] address, long scopeid);
Sample Code:
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: TestClass testClass = new TestClass();
6:
7: using (MemoryStream stream = new MemoryStream())
8: {
9: XmlSerializer ser = new XmlSerializer(typeof(TestClass));
10: ser.Serialize(stream, testClass);
11: string result = Encoding.UTF8.GetString(stream.ToArray());
12: }
13: }
14: }
15:
16: public class TestClass
17: {
18: public IPAddress IP { get; set; }
19: }
Running prompt:
Solution: Expand IPAddress:
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: TestClass testClass = new TestClass();
6: testClass.IP.IPAddressAsString = "127.0.0.1";
7:
8: using (MemoryStream stream = new MemoryStream())
9: {
10: XmlSerializer ser = new XmlSerializer(typeof(TestClass));
11: ser.Serialize(stream, testClass);
12: string result = Encoding.UTF8.GetString(stream.ToArray());
13: }
14: }
15: }
16:
17: public class TestClass
18: {
19: public IPAddressEx IP { get; set; }
20:
21: public TestClass()
22: {
23: this.IP = new IPAddressEx();
24: }
25: }
26:
27: public class IPAddressEx
28: {
29: [XmlElement(ElementName = "IPAddress")]
30: public string IPAddressAsString
31: {
32: get { return IPAddress != null ? IPAddress.ToString() : null; }
33: set
34: {
35: IPAddress ip;
36: if (value != null && IPAddress.TryParse(value, out ip))
37: IPAddress = ip;
38: else
39: IPAddress =null;
40: }
41: }
42: [XmlIgnore]
43: public IPAddress IPAddress { get; set; }
44: }
Serialization result:
1: <?xml version="1.0"?>
2: <TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
3: <IP>
4: <IPAddress>127.0.0.1</IPAddress>
5: </IP>
6: </TestClass>
6: </TestClass>