简体   繁体   English

XmlDocument忽略的只读属性

[英]Read-only property ignored by XmlDocument

I have a model with some properties: 我有一个具有一些属性的模型:

public class Invoice
{
    public string InvoiceNumber { get; set; }

    [NotMapped]
    public string Title
    {
        get
        {
            string title = "";
            //some algorithm
            return title;
        }
    }
}

My model has two properties: One of them is read-only (Title) as it's generated programmatically. 我的模型具有两个属性:其中之一是只读(标题),因为它是通过程序生成的。

I'm generating a XMLDocument from this model (generic approach): 我正在从该模型生成XMLDocument(通用方法):

private XmlDocument GenerateXmlDocument()
{
    XmlDocument xmlDocument = new XmlDocument();
    XmlSerializer xmlSerializer = new XmlSerializer(_objectToSerialize.GetType());
    using (MemoryStream xmlStream = new MemoryStream())
    {
        xmlSerializer.Serialize(xmlStream, _objectToSerialize);
        xmlStream.Position = 0;
        xmlDocument.Load(xmlStream);
    }

    //Set namespace
    xmlDocument.DocumentElement.SetAttribute("xmlns", XmlNamespace);

    return xmlDocument;
}

However it seems my read-only property isn't read by GenerateXmlDocument . 但是,似乎我的只读属性没有被GenerateXmlDocument读取。 How to solve this issue? 如何解决这个问题?

The XMLSerializer will not Serialize readonly properties. XMLSerializer不会序列化只读属性。 This is a limitation. 这是一个限制。 However you should serialize the field "title" anyways. 但是,无论如何,您都应该序列化“标题”字段。 To do that you could use the DataContractSerializer. 为此,您可以使用DataContractSerializer。 It is more powerful and allows to serialize the fields you are using within your getter. 它功能更强大,可以序列化您在getter中使用的字段。

See: https://msdn.microsoft.com/en-us/library/mt693218.aspx 请参阅: https//msdn.microsoft.com/zh-cn/library/mt693218.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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