سؤال

After read multiples posts related on this error and not found an solution to my problem, I explain it here.

I use XmlSerializer to serialize simple classes.

Here's my code:

    private void btnGenerateXml_Click(object sender, RoutedEventArgs e)
    {
        Orchard orchard = new Orchard
        {
            Recipe = new Recipe
            {
                Name = "Generated by JooWeb.Tools",
                Author = "admin",
                ExportUtc = DateTime.UtcNow
            },
            MyDatas = new MyDatas
            {
                //Test = "test"
                TrendDatas = new TrendDatas
                {
                    Id = null,
                    Status = "Published",
                    TrendDatasPart = new TrendDatasPart
                    {
                        IdSource = 0,
                        PostalCode = "1000",
                        Locality = "Test5",
                        Surface = (decimal)0.00,
                        Price = (decimal)0.00,
                        Type = "",
                        InsertDateIndicator = "",
                        UpdateDateIndicator = "",
                        GetFromDate = DateTime.Now,
                        UpdatedDate = new DateTime(1900, 1, 1)
                    },
                    CommonPart = new CommonPart
                    {
                        Owner = "/User.UserName=admin",
                        CreatedUtc = DateTime.UtcNow,
                        PublishedUtc = DateTime.UtcNow,
                        ModifiedUtc = DateTime.UtcNow
                    }
                }
            }
        };

        XmlSerializer orchardXmlSerializer = new XmlSerializer(typeof(Orchard));
        var path = @"C:\Temp\orchardFileImport_" + string.Format("{0:yyyyMMdd}", DateTime.Today) + ".xml";
        if (File.Exists(path))
            File.Delete(path);
        orchardXmlSerializer.Serialize(File.OpenWrite(path), orchard);
        MessageBox.Show("Finished");
    }
}

[XmlRoot]
public class Orchard
{
    [XmlElement]
    public Recipe Recipe { get; set; }
    [XmlElement(ElementName = "Data")]
    public MyDatas MyDatas { get; set; }
}

public class Recipe
{
    [XmlElement]
    public string Name { get; set; }
    [XmlElement]
    public string Author { get; set; }
    [XmlElement]
    public DateTime ExportUtc { get; set; }
}

public class MyDatas
{
    public MyDatas()
    {

    }

    //[XmlElement]
    //public string Test { get; set; }

    [XmlElement]
    public TrendDatas TrendDatas { get; set; }
}

public class TrendDatas
{
    [XmlAttribute]
    public string Status { get; set; }
    [XmlAttribute]
    public int? Id { get; set; }
    //[XmlIgnore]
    [XmlElement]
    public TrendDatasPart TrendDatasPart { get; set; }
    //[XmlIgnore]
    [XmlElement]
    public CommonPart CommonPart { get; set; }
}

public class TrendDatasPart
{
    [XmlAttribute]
    public int IdSource { get; set; }
    [XmlAttribute]
    public string PostalCode { get; set; }
    [XmlAttribute]
    public string Locality { get; set; }
    [XmlAttribute]
    public decimal Surface { get; set; }
    [XmlAttribute]
    public decimal Price { get; set; }
    [XmlAttribute]
    public string Type { get; set; }
    [XmlAttribute]
    public string InsertDateIndicator { get; set; }
    [XmlAttribute]
    public string UpdateDateIndicator { get; set; }
    [XmlAttribute]
    public DateTime GetFromDate { get; set; }
    [XmlAttribute]
    public DateTime UpdatedDate { get; set; }
}

public class CommonPart
{
    [XmlAttribute]
    public string Owner { get; set; }
    [XmlAttribute]
    public DateTime CreatedUtc { get; set; }
    [XmlAttribute]
    public DateTime PublishedUtc { get; set; }
    [XmlAttribute]
    public DateTime ModifiedUtc { get; set; }
}

With this code when I click on Generate xml file, I got the error InvalidOperationException There was an error reflecting type 'MergeExcelFiles.Orchard'. {"There was an error reflecting property 'MyDatas'."}

Like you see in my comments, I try to just add a string xmlElement to node MyDatas, with this change I got no error but in the xml file I don't have any node with name Data.

I don't understand why with class Recipe all look right but with node MyDatas nothing showed in xml file or got this error "InvalidOperationException".

هل كانت مفيدة؟

المحلول

You need to dig into your error message more because the reason is in the innermost exception:

System.InvalidOperationException: Cannot serialize member 'Id' of type System.Nullable`1[System.Int32]. XmlAttribute/XmlText cannot be used to encode complex types.

The issue is that you have a nullable value type as a property (TrendDatas.Id) to be serialized as an attribute and XmlSerializer does not handle these well. There are a number of workarounds listed here and here. None of them is particularly elegant. The best option might be changing the definition of Id to an element:

public class TrendDatas
{
    // ... snip ...

    [XmlElement(IsNullable = true)]
    public int? Id { get; set; }

    public bool ShouldSerializeId() { return Id.HasValue; }

    // ... snip ...
}

The ShouldSerializeId is a method that, by convention, the serializer uses to decide if the property should be serialized in the output. In the case of a null value, no element will be defined in the serialized output.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top