-2

I need my WCF to be able to receive a request with the following structure.

<MyRequest>
       <Product>
             ...attributes
       </Product>
        <Product>
             ...attributes
        </Product>
        <Document>
              ...attributes
        </Document>
</MyRequest>

when creating the data contract and adding the DataMember and XmlElement decorators for the List type attribute, however, I can't get it to receive the list without a container.

[DataContract]
public class MyRequest
{
    [DataMember(Order = 0)]
    [XmlElement("Product")]
    public List<Product> Products { get; set; }

    [DataMember(Order = 1)]
    [XmlElement("Document")]
    public Document Document { get; set; }

    public MyRequest()
    {
        Products = new List<Product>();
        Document = new Document();
    }
}

[DataContract]
public class Product
{
    // ...
}

[DataContract]
public class Document
{
    // ...
}
dbc
  • 104,963
  • 20
  • 228
  • 340
  • You cannot avoid the outer container element when using `List` with `DataContractSerializer`, see [Data Contract Serializer - How to omit the outer element of a collection](https://stackoverflow.com/q/8591045). You will need to switch to `XmlSerializer`, by applying `[XmlSerializerFormat]` to your service contract, see [How to change Wcf to use a different serializer?](https://stackoverflow.com/q/4050938) or [Creating XML childs, omit parent node](https://stackoverflow.com/a/59725871/3744182). – dbc Aug 25 '23 at 00:16
  • Do those questions answer yours? The other option I can think of would be for `MyRequest` to implement `IXmlSerializable` which is a considerable nuisance and so not recommended. – dbc Aug 25 '23 at 00:18
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 25 '23 at 08:00
  • 1
    .Net has two separate XML serializers, [DataContractSerializer](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datacontractserializer?view=netframework-4.8) and [XmlSerializer](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=netframework-4.8). When you use XmlSerializer instead of DataContractSerializer, you need to use the XmlSerializerFormatAttribute attribute. Or you have another idea to realize it? – Jiayao Aug 25 '23 at 09:11

0 Answers0