简体   繁体   中英

XmlSerializer serializes but doesn't deserialize

I'm using the XmlSerializer class from System.Xml.Serialization My datatypes are marked with the appropriate attributes eg

[XmlRoot(ElementName = "XMLFile")]
public class OrderXml
{
    [XmlArray(ElementName = "SalesOrders")]
    [XmlArrayItem(ElementName = "SalesOrder")]
    public List<SalesOrder> SalesOrders { get; set; }

    public OrderXml()
    {

    }
}

When serializing, there are no problems.

using (FileStream fs = new FileStream(save_to_path + $"Orders_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xml", FileMode.Create))
{
    xs.Serialize(fs, new OrderXml() { SalesOrders = order_resp.results });
}

However, when attempting to read the files that this program has written, there are no exceptions but all of the fields have default values:

OrderXml ox = null;
using(Stream s = new FileStream(file, FileMode.Open))
{
    ox = (OrderXml)xs.Deserialize(s);
}

What have I missed that allows serialize to work, but prevents deserialize from working properly?

I've found the problem. And it has nothing to do with XmlSerilizer.

Up until recently, this program was being used only to write files. Many (most) of the properties written have getters, but no setters because of the above.

The object's fields are written from deserializing a JSON body of a web request and the properties written to the xml file are calculated from these.

For example:

[XmlElement(ElementName = "DeliveryNet")]
public decimal DeliveryNet { get { return Math.Round((100M * price_delivery) / (fee.vat_rate + 100M), 2); } set { } }

I just need to make these blank setters actually do something, then it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM