I have problem with deserialize XML my xml code is:
<?xml version="1.0" encoding="UTF-8"?>
<Plc name="Test" vendor="S" >
<connection name="Plc" model="S2" address="192.168.0.1" pooling="1.0" slot="0" rack="0" active="true" frameLength="200">
<tag name="DBTimeMean" address="DB100.DBD628.0" />
<tag name="DBTimeMax1" address="DB100.DBD632.0" />
<tag name="DBTimeMax2" address="DB100.DBD636.0" />
<tag name="DBTimeMin" address="DB100.DBD640.0" />
<tag name="MachineStatusID" address="DB100.DBD644.0" />
</connection>
</Plc>
and this is my object class :
public class PlcPointFormat
{
[XmlRoot(ElementName = "tag")]
public class Tag
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "address")]
public string Address { get; set; }
}
[XmlRoot(ElementName = "connection")]
public class Connection
{
[XmlElement(ElementName = "tag")]
public ObservableCollection<Tag> Tag { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "model")]
public string Model { get; set; }
[XmlAttribute(AttributeName = "address")]
public string Address { get; set; }
[XmlAttribute(AttributeName = "pooling")]
public string Pooling { get; set; }
[XmlAttribute(AttributeName = "slot")]
public string Slot { get; set; }
[XmlAttribute(AttributeName = "rack")]
public string Rack { get; set; }
[XmlAttribute(AttributeName = "active")]
public string Active { get; set; }
[XmlAttribute(AttributeName = "frameLength")]
public string FrameLength { get; set; }
}
[XmlRoot(ElementName = "Plc")]
public class Plc
{
[XmlElement(ElementName = "connection")]
public Connection Connection { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "vendor")]
public string Vendor { get; set; }
}
private static XmlSerializer getSerializer()
{
if (formatDataListXmlSerializer == null)
{
formatDataListXmlSerializer = new XmlSerializer(typeof(PlcPointFormat));
}
return formatDataListXmlSerializer;
}
public string SerializeToXML()
{
XmlSerializer xsSubmit = getSerializer();
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings() { Indent = true }))
{
xsSubmit.Serialize(writer, this);
xml = sww.ToString();
}
}
return xml;
}
private static XmlSerializer formatDataListXmlSerializer = null;
public static PlcPointFormat CreateFromXML(string xml)
{
//PlcPointFormat ret;
XmlSerializer serializer = getSerializer();
try
{
StringReader reader = new StringReader(xml);
var ret = serializer.Deserialize(reader);
reader.Close();
}
catch
{
//ret = new PlcPointFormat();
}
return null;
}
}
Every time i try to invoke method CreateFromXML with xml above as parameter I got null. Do you have any suggestions? I tried to specify encoding it doesn't make any affect. I am using .net 4.6 .2 in this project and System.XMl.Serialization namespace for deserialization and serialization.