Nest XML Elements - XML Serialization - c#

I need to sandwich an element inside of another element. Is it possible to serialize XML like this?
http://pastebin.com/7qDE7Ses
Here is my class
[XmlRoot(ElementName = "SalesOrderMod")]
public partial class SalesOrderMod
{
[XmlElementAttribute(Order = 1)]
public string TxnID { get; set; }
[XmlElementAttribute(Order = 2)]
public string EditSequence { get; set; }
[XmlElementAttribute(Order = 3)]
public string ShipDate { get; set; }
[XmlElementAttribute(Order = 4)]
public ListRef ShipMethodRef = new ListRef();
public bool ShouldSerializeShipMethodRef()
{
return !(String.IsNullOrEmpty(ShipMethodRef.FullName));
}
[XmlElementAttribute(Order = 5)]
public string Other { get; set; }
[XmlElementAttribute(Order = 6, ElementName = "SalesOrderLineMod")]
public List<LineMod> SalesOrderLineMod = new List<LineMod>();
[XmlElementAttribute(Order = 7, ElementName = "SalesOrderLineGroupMod")]
public List<LineMod> SalesOrderLineGroupMod = new List<LineMod>();
}

You originally indicated you would like to serialize a series of elements inside an XML document like so:
<SalesOrderLineRet>
</SalesOrderLineRet>
<SalesOrderLineGroupRet>
</SalesOrderLineGroupRet>
<SalesOrderLineRet>
</SalesOrderLineRet>
You can if the types that correspond to SalesOrderLineRet and SalesOrderLineGroupRet have some common base type T, and they are stored in a List<T>. For instance, the following class definitions:
public abstract class SalesOrderLineRetBase
{
}
public class SalesOrderLineRet : SalesOrderLineRetBase
{
}
public class SalesOrderLineGroupRet : SalesOrderLineRetBase
{
}
public class RootObject
{
[XmlElement(typeof(SalesOrderLineRetBase))]
[XmlElement(typeof(SalesOrderLineRet))]
[XmlElement(typeof(SalesOrderLineGroupRet))]
public List<SalesOrderLineRetBase> SalesOrders { get; set; }
}
Will, when serialized, produce the following XML:
<RootObject>
<SalesOrderLineRet />
<SalesOrderLineGroupRet />
</RootObject>
Using [XmlElement(typeof(T))] tells XmlSerializer that the list should be serialized without an outer container element, and that items of type T can be expected to be found in the list. You must apply [XmlElement(typeof(T))] once for each type T that will be stored in the list.
(You can use List<object> if the types in the list have no other more derived base type, however I don't recommend that. I would instead recommending grouping the possible types of list entry under a specific base type.)
If you would prefer your list to be serialized with an outer container element, you can use [XmlArray] and [XmlArrayItem(typeof(T))]:
public abstract class SalesOrderLineRetBase
{
}
public class SalesOrderLineRet : SalesOrderLineRetBase
{
}
public class SalesOrderLineGroupRet : SalesOrderLineRetBase
{
}
public class RootObject
{
[XmlArray("SalesOrders")]
[XmlArrayItem(typeof(SalesOrderLineRetBase))]
[XmlArrayItem(typeof(SalesOrderLineRet))]
[XmlArrayItem(typeof(SalesOrderLineGroupRet))]
public List<SalesOrderLineRetBase> SalesOrders { get; set; }
}
Which produces the following XML:
<RootObject>
<SalesOrders>
<SalesOrderLineRet />
<SalesOrderLineGroupRet />
</SalesOrders>
</RootObject>
You must apply [XmlArrayItem(typeof(T))] for each type T that will be stored in the list.
(Since you don't include the relevant classes and XML in your question, I'm not sure which one you might want.)

Related

C# XML Serialization - Custom ordering based on data [duplicate]

I have the following test XML string:
<?xml version="1.0" encoding="UTF-8"?>
<test id="myid">
<b>b1</b>
<a>a2</a>
<a>a1</a>
<b>b2</b>
</test>
which I deserialize using this class:
[XmlRoot(ElementName = "test")]
public class Test
{
[XmlElement(ElementName = "a")]
public List<string> A { get; set; }
[XmlElement(ElementName = "b")]
public List<string> B { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
If I'm now going to serialize the object the result will be:
<?xml version="1.0" encoding="utf-16"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="myid">
<a>a2</a>
<a>a1</a>
<b>b1</b>
<b>b2</b>
</test>
Is there a way to keep the initial sort order?
I guess I can't use [XmlElementAttribute(Order = x)] cause the order shouldn't be hardcoded but identically with the initial xml.
I thought about adding an order property to my lists like that
[XmlRoot(ElementName="a")]
public class A
{
[XmlAttribute(AttributeName="order")]
public string Order { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="b")]
public class B
{
[XmlAttribute(AttributeName="order")]
public string Order { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName="test")]
public class Test
{
[XmlElement(ElementName="a")]
public List<A> A { get; set; }
[XmlElement(ElementName="b")]
public List<B> B { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
but I don't know how to order by them when serializing.
You can do this with XmlSerializer by using a single collection to capture both the <a> and <b> elements and applying the [XmlElement(Name, Type = typeof(...))] attribute to it multiple times, once for each desired element name. Because you are using a single collection to deserialize both elements, the order is automatically preserved. However, to make this work, XmlSerializer must be able to determine the correct element name when re-serializing. There are two approaches to accomplish this, as documented in Choice Element Binding Support:
If the collection contains polymorphic items, the element name can be mapped to the concrete item type by using the [XmlElementAttribute(String, Type)] constructor. For instance, if you have a sequence of elements that might be strings or integers like so:
<Things>
<string>Hello</string>
<int>999</int>
</Things>
This can be bound to a collection as follows:
public class Things
{
[XmlElement(Type = typeof(string)),
XmlElement(Type = typeof(int))]
public List<object> StringsAndInts { get; set; }
}
If the collection contains only a single type of item, the element name can be encoded in an associated array of enum values, where the enum names correspond to the element names and the array itself is identified via the [XmlChoiceIdentifierAttribute] attribute.
For details, see the documentation examples.
I find option #1 easier to work with than option #2. Using this approach, the following model will deserialize and re-serialize your XML while successfully preserving the order of the <a> and <b> elements:
public abstract class StringElementBase
{
[XmlText]
public string Text { get; set; }
public static implicit operator string(StringElementBase element)
{
return element == null ? null : element.Text;
}
}
public sealed class A : StringElementBase
{
}
public sealed class B : StringElementBase
{
}
[XmlRoot(ElementName = "test")]
public class Test
{
[XmlElement("a", Type = typeof(A))]
[XmlElement("b", Type = typeof(B))]
public List<StringElementBase> Items { get; } = new List<StringElementBase>();
[XmlIgnore]
// For convenience, enumerate through the string values of the items.
public IEnumerable<string> ItemValues { get { return Items.Select(i => (string)i); } }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
Working .Net fiddle.
For more examples of using [XmlChoiceIdentifier] to deserialize a sequence of elements with different names to c# objects of the same type, see for instance here or here.
No, basically; XmlSerializer doesn't support that. If you want to use that option you'd need to write it manually with XDocument or XmlDocument or XmlReader.

serialize derived class member using XmlChoiceIdentifierAttribute

I have WSDL service class in which I would like to add extra properties. When I am trying to deserialize my derived class its giving error "You need to add XmlChoiceIdentifierAttribute to the 'ObjCreatePaperClipTransaction' member."
Here is the code I wrote on top of service classes. (executeCreatePaperClipTransaction & CreatePaperClipTransactionType are classes from proxy object)
namespace MyProject.DTO
{
[XmlType("executeCreatePaperClipTransaction")]
public partial class CustomExecuteCreatePaperClipTransaction : executeCreatePaperClipTransaction
{
[XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
[XmlElement("CreatePaperClipTransaction")]
public CustomCreatePaperClipTransactionType ObjCreatePaperClipTransaction { get; set; }
}
public partial class CustomCreatePaperClipTransactionType : CreatePaperClipTransactionType
{
[XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public executeCreateLoanIncrease ObjLoanIncreaseRequest { get; set; }
[XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
public executeCreateFreeFormEventFeePayment ObjFreeFormEventFeePaymentRequest { get; set; }
}
}
When I remove [XmlElement("CreatePaperClipTransaction")] line, its working fine. But in the seralized xml i want tag name to be CreatePaperClipTransaction and not ObjCreatePaperClipTransaction
I went through this answer but I am not sure how can i implement in my case https://stackoverflow.com/a/20379038/1169180
Rather than adding two separate [XmlElement] attributes to your ObjCreatePaperClipTransaction property, you should add one single attribute with all necessary information:
[XmlType("executeCreatePaperClipTransaction")]
public partial class CustomExecuteCreatePaperClipTransaction : executeCreatePaperClipTransaction
{
[XmlElement(ElementName = "CreatePaperClipTransaction", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public CustomCreatePaperClipTransactionType ObjCreatePaperClipTransaction { get; set; }
}
Working .Net fiddle.
When you add multiple [XmlElement] attributes to a property, you are informing XmlSerializer that multiple different XML element names should be bound to the same property, for instance because the property value is polymorphic:
public class BaseClass
{
}
public class DerivedClass : BaseClass
{
}
public class RootObject
{
[XmlElement(ElementName = "BaseClassProperty", Type = typeof(BaseClass))]
[XmlElement(ElementName = "DerivedClassProperty", Type = typeof(DerivedClass))]
public BaseClass Property { get; set; }
}
In the example above, if the Property is assigned a DerivedClass value, the following XML will be generated:
<RootObject>
<DerivedClassProperty />
</RootObject>
That doesn't seem to apply here. You just want to bind your property to the XML element name <CreatePaperClipTransaction>.

DataContractJsonSerializer: collection type cannot be serialized when assigned to an interface

I am writing a WCF service that generates various XML and JSON formats for multiple clients. The code below generates a SerializationException: 'TPH_PriceListJsonItems' is a collection type and cannot be serialized when assigned to an interface type that does not implement IEnumerable ('TPH_IPriceListItems'). The XML part is working fine, but not JSON. I do not understand the error, my interface is implementing IEnumerable to represent a class wrapping a simple List<> so I can use the CollectionDataContract.
public class ReproduceDataContractIssue
{
public static void Main(String[] args)
{
// Create test object - vacation products lowest prices grid
TPH_IPriceList priceList = new TPH_PriceListJson();
priceList.ListItems.Add(new TPH_PriceListJsonItem() { DestCityName = "Cancun", StayDuration = 7, LowestPrice = 1111 });
priceList.ListItems.Add(new TPH_PriceListJsonItem() { DestCityName = "Jamaica", StayDuration = 14, LowestPrice = 2222 });
// Serialize into XML string
DataContractSerializer serializer = new DataContractSerializer(priceList.GetType());
MemoryStream memStream = new MemoryStream();
serializer.WriteObject(memStream, priceList);
memStream.Seek(0, SeekOrigin.Begin);
string xmlOutput;
using (var streamReader = new StreamReader(memStream))
xmlOutput = streamReader.ReadToEnd();
// Serialize into JSON string
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(priceList.GetType());
jsonSerializer.WriteObject(memStream = new MemoryStream(), priceList);
memStream.Seek(0, SeekOrigin.Begin);
string jsonOutput;
using (var streamReader = new StreamReader(memStream))
jsonOutput = streamReader.ReadToEnd();
}
}
public interface TPH_IPriceList
{
TPH_IPriceListItems ListItems { get; set; }
}
public interface TPH_IPriceListItems : IEnumerable<TPH_IPriceListItem>, IEnumerable, IList<TPH_IPriceListItem>
{
}
public interface TPH_IPriceListItem
{
string DestCityName { get; set; }
int StayDuration { get; set; }
int LowestPrice { get; set; }
}
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[DataMember]
public TPH_IPriceListItems ListItems { get; set; }
public TPH_PriceListJson()
{
ListItems = new TPH_PriceListJsonItems();
}
}
[DataContract]
public class TPH_PriceListJsonItem : TPH_IPriceListItem
{
[DataMember(Order = 1)]
public string DestCityName { get; set; }
[DataMember(Order = 2)]
public int StayDuration { get; set; }
[DataMember(Order = 3)]
public int LowestPrice { get; set; }
public TPH_PriceListJsonItem()
{
}
}
[CollectionDataContract(Name = "ListItems", ItemName = "ListItem")]
[KnownType(typeof(TPH_PriceListJsonItem))]
public class TPH_PriceListJsonItems : List<TPH_IPriceListItem>, TPH_IPriceListItems, IEnumerable<TPH_IPriceListItem>, IEnumerable
{
public TPH_PriceListJsonItems(int capacity)
: base(capacity)
{
}
public TPH_PriceListJsonItems()
: base()
{
}
}
}
The inconsistency arises from a difference in how JSON and XML represent collections. For XML, the data contract serializers convert a collection to a nested set of elements -- an outer collection wrapper, and an inner element for each item in the collection. For JSON, the serializers convert a collection to an array containing objects. This seems reasonable, but there's a difference between the two: the XML outer element can have its own XML attributes, but JSON arrays cannot have their own properties -- there's simply no place for them in the standard.
This becomes an issue in dealing with type hints. Type hints are properties added to the serialized data to indicate, in the event of serializing an interface or base class of a class hierarchy, what concrete class was actually serialized. They are required to enable deserialization of the object without data loss. In XML, they appear as an i:type attribute:
<PriceList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Question32569055.V1">
<ListItems i:type="ListItems"> <!-- Notice the type hint here. -->
<ListItem i:type="TPH_PriceListJsonItem"> <!-- Notice the type hint here also. -->
<DestCityName>Cancun</DestCityName>
<StayDuration>7</StayDuration>
<LowestPrice>1111</LowestPrice>
</ListItem>
</ListItems>
</PriceList>
As you can see from your own example, type hints can be added for both collection and non-collection classes.
In JSON objects, they appear as an added property named "__type":
{
"__type": "TPH_PriceListJsonItem:#Question32569055.V3",
"DestCityName": "Cancun",
"StayDuration": 7,
"LowestPrice": 1111
}
But, as mentioned before, JSON arrays cannot have properties. So, what does DataContractJsonSerializer do for polymorphic collection types? Well, other than for a few standard collection interfaces which, as Fabian notes, are mapped to collection classes using hardcoded logic, it throws a cryptic exception to indicate that subsequent deserialization would be impossible. (For comparison, Json.NET introduces an extra container object to hold collection type information. See TypeNameHandling setting.)
The solution to this inconsistency is to serialize the collection explicitly as a concrete collection (TPH_PriceListJsonItems in your case) rather than as an interface:
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[IgnoreDataMember]
public TPH_IPriceListItems ListItems
{
get
{
return ListItemList;
}
set
{
var list = value as TPH_PriceListJsonItems;
if (list == null)
{
list = new TPH_PriceListJsonItems();
if (value != null)
list.AddRange(value);
}
ListItemList = list;
}
}
[DataMember(Name = "ListItems")]
TPH_PriceListJsonItems ListItemList { get; set; }
public TPH_PriceListJson()
{
ListItemList = new TPH_PriceListJsonItems();
}
}
This eliminates the need for the type hint on the collection element while retaining it for collection members. It generates the following XML:
<PriceList xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Question32569055.V3">
<ListItems> <!-- No type hint here any more. -->
<ListItem i:type="TPH_PriceListJsonItem"> <!-- But the type hint is still here. -->
<DestCityName>Cancun</DestCityName>
<StayDuration>7</StayDuration>
<LowestPrice>1111</LowestPrice>
</ListItem>
</ListItems>
</PriceList>
And produces the following JSON:
{
"ListItems": [
{
"__type": "TPH_PriceListJsonItem:#Question32569055.V3",
"DestCityName": "Cancun",
"StayDuration": 7,
"LowestPrice": 1111
},
]
}
This design allows the class TPH_IPriceListItems to control exactly what type of collection is used internally rather than leaving it up to users of the class, and thus seems like a preferable design overall.
Looks like it is a similar problem to this one. The List of supported interfaces in DataContractJsonSerializer is hardcoded. So you can't add your own List Wrapper interface.
Why don't you just drop TPH_IPriceListItems like in the following code ? It is simpler and should also do what you want:
public interface TPH_IPriceList
{
IList<TPH_IPriceListItem> ListItems { get; set; }
}
public interface TPH_IPriceListItem
{
string DestCityName { get; set; }
int StayDuration { get; set; }
int LowestPrice { get; set; }
}
[DataContract(Name = "PriceList")]
[KnownType(typeof(TPH_PriceListJsonItems))]
public class TPH_PriceListJson : TPH_IPriceList
{
[DataMember]
public IList<TPH_IPriceListItem> ListItems { get; set; }
public TPH_PriceListJson()
{
ListItems = new TPH_PriceListJsonItems();
}
}
[DataContract]
public class TPH_PriceListJsonItem : TPH_IPriceListItem
{
[DataMember(Order = 1)]
public string DestCityName { get; set; }
[DataMember(Order = 2)]
public int StayDuration { get; set; }
[DataMember(Order = 3)]
public int LowestPrice { get; set; }
}
[CollectionDataContract(Name = "ListItems", ItemName = "ListItem")]
[KnownType(typeof(TPH_PriceListJsonItem))]
public class TPH_PriceListJsonItems : List<TPH_IPriceListItem>
{
}

XML serialization - bypass container class?

I am trying to serialize an object in a particular manner. The main class has a container class that holds some attributes, but really these attributes should be on the main class, from the point of view of the schema. Is there a way to bypass the container class and treat the properties on the container class as properties on the main class, for the purposes of serialization?
I am trying to create XML along the lines of:
<Main foo="3" bar="something">
<Others>etc</Others>
</Main>
from this code:
[System.Xml.Serialization.XmlRootAttribute("Main", Namespace = "")]
public class MainObject
{
public HelperContainer { get; set; }
public string Others { get; set; }
}
public class HelperContainer
{
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "foo")]
public int Foo { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "bar")]
public string Bar { get; set; }
}
You may want to try implementing IXmlSerializable on MainObject to be able to control what happens when calling serialize. For the read and write xml methods specify the fields to serialize.
Check out msdn: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx
Something like:
public class MainObject : IXmlSerializable
{
public HelperContainer { get; set; }
public string Others { get; set; }
public void WriteXml (XmlWriter writer)
{
writer.WriteString(Others);
writer.WriteAttributeString("foo", HelperContainer.Foo);
writer.WriteAttributeString("bar", HelperContainer.Bar);
}
public void ReadXml (XmlReader reader)
{
Others = reader.ReadString();
//...
}
}

C# XML Serialization - How to Serialize attribute in Class that inherits List<Object>?

I need to create an XML file using C#.
I am using a class that inherits List that represents a list of computers and later initialize it with values but the serializer doesn't get the attributes for this class, only for its descendants.
this is the class:
public class Computers : List<Computer>
{
[XmlAttribute("StorageType")]
public int StorageType { get; set; }
[XmlAttribute("StorageName")]
public string StorageName { get; set; }
}
public class Computer
{
[XmlAttribute("StorageType")]
public int StorageType { get; set; }
[XmlAttribute("StorageName")]
public string StorageName { get; set; }
public string IPAddress { get; set; }
public string Name { get; set; }
}
The result should look something like this:
<fpc4:Computers StorageName="Computers" StorageType="1">
<fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1">
<fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress>
<fpc4:Name dt:dt="string">Computer1</fpc4:Name>
</fpc4:Computer>
<fpc4:Computer StorageName="{AFE5707C-EA71-4442-9CA8-2A6264EAA814}" StorageType="1">
<fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress>
<fpc4:Name dt:dt="string">Computer2</fpc4:Name>
</fpc4:Computer>
But what I get so far is this:
<fpc4:Computers>
<fpc4:Computer StorageType="1" StorageName="{7297fc09-3142-4284-b2e9-d6ea2fb1be78}">
<fpc4:IPAddress>127.0.0.1</fpc4:IPAddress>
<fpc4:Name>Computer1</fpc4:Name>
</fpc4:Computer>
<fpc4:Computer StorageType="1" StorageName="{eab517f6-aca9-4d01-a58b-143f2e3211e7}">
<fpc4:IPAddress>127.0.0.1</fpc4:IPAddress>
<fpc4:Name>Computer2</fpc4:Name>
</fpc4:Computer>
</fpc4:Computers>
As you can see the Computers node which is the parent node doesn't get the attributes.
Do you guys have a solution?
XmlSerializer treats lists completely separate to leaf nodes; properties on lists do not exist - it is just a collection of the contained data. A better approach would be:
public class Computers {
private readonly List<Computer> items = new List<Computer>();
[XmlElement("Computer")]
public List<Computer> Items { get { return items; } }
[XmlAttribute("StorageType")]
public int StorageType { get; set; }
[XmlAttribute("StorageName")]
public string StorageName { get; set; }
}
This is an object that has a set of computers and has two attributes - but is not a list itself. The use of XmlElementAttribute for the list flattens the nesting as desired. Note that I have omitted namespaces for convenience.
Inheriting from a list (with an aim of adding members) will not work well, not just for XmlSerlaizer, but for a wide range of serializers and binding frameworks.

Categories

Resources