I am using c# and the XmlSerialiser class to create xml from DTO Objects.
Now I have to generate such xml text:
<Order>
<OrderNo>123456</OrderNo>
<Positions>
<TextPosition>
<Text>This is Order No 123456</Text>
</TextPosition>
<ItemPosition>
<ItemId>14789</ItemId>
<ItemName>Product 1</ItemName>
</ItemPosition>
</TextPosition>
<ItemPosition>
<ItemId>456</ItemId>
<ItemName>Product 2</ItemName>
</ItemPosition>
<TextPosition>
<Text>Good bye</Text>
</TextPosition>
<SumPosition>
<Value>123.45 USD</Value>
</SumPosition>
</Positions>
</Order>
I use Attributes to decorate my classes and everything works fine.
One thing I couldn’t solve yet. I need to generate a tag Positions with different tag TextPosition, ItemPosition, ValuePosition, ... inside.
How do I achive this in c#?
Currently my class Order contains a
[XmlElement("Positions")]
public PositionList Positions { get; set; }
PositionList is a class with
public class PositionList
{
[XmlElement("Positions")]
public List<Object> Positions { get; set; }
}
In order to avoid a InvalidOperationException I added
[XmlInclude(typeof(Textposition))]
[XmlInclude(typeof(ItemPosition))]
[XmlInclude(typeof(SumPosition))]
to my Order class.
However, instead of generating
<Positions>
<TextPosition>...</TextPosition>
</Positions>
the serializer generates:
<Position d4p1:type="TextPosition" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">...</Position>
The thing is, In don’t need to deserialize it my self but provide a XML-file in a very strict format for one customer. Is there a way to achive this?
There is a way:
Example serializing it to an XML file:
Result: