Reputation: 6458
I'm getting an error when I try to serialize my class. The xml schema is defined by a third-party and I can't change it.
The xml looks like this (snippet only btw):
<order>
<date type="received-date">20160810</date>
<date type="required-date">20160810</date>
<reference type="cust-order-no">CCCC</reference>
<reference type="an-2">AAAA</reference>
<reference type="an-3">BBBB</reference>
<order>
I've defined the following class for my order date
[Serializable]
public class OrderDate
{
public enum OrderDateTypeEnum
{
[Description("entered-date")]
EnteredDate,
[Description("received-date")]
ReceivedDate,
[Description("required-date")]
RequiredDate
}
private OrderDateTypeEnum _typeEnum;
[XmlIgnore]
public OrderDateTypeEnum TypeEnum
{
get { return this._typeEnum; }
set
{
this._typeEnum = value;
this.Type = this._typeEnum.GetDescription();
}
}
[XmlAttribute("type")]
public string Type { get; set; }
[XmlText]
public string Name { get; set; }
}
and the order class is defined as:
[Serializable]
public class Order
{
[XmlElement("date")]
public OrderDate EnteredDate { get; set; }
[XmlElement("date")]
public OrderDate ReceivedDate { get; set; }
[XmlElement("date")]
public OrderDate RequiredDate { get; set; }
}
but when I serialize this, I get an error:
The XML element 'date' from namespace '' is already present in the current
scope. Use XML attributes to specify another XML name or namespace for the
element.
When I remove the [XmlElement("date")]
, it works but my xml is not formatted the way I needed it to.
I'll have the exact same problem with reference when I get to it.
How can I circumvent this problem?
Upvotes: 0
Views: 1808
Reputation: 26213
You can't do this and map to Order
as you've defined it without implementing IXmlSerializable
yourself. What you can do is use a single List<OrderDate>
property:
[XmlRoot("order")]
public class Order
{
[XmlElement("date")]
public List<OrderDate> Dates { get; set; }
}
See this fiddle for a working demo. You could add various (ignored) properties to query the dates for each type if you wished.
As an aside, the [Serializable]
attribute has nothing to do with XmlSerializer
and can be removed.
Upvotes: 1