Search code examples
c#xmldeserializationxmlserializerdatacontractserializer

WCF error: Expecting state 'Element'.. Encountered 'Text' with name '', namespace '' post call in XML format


I have a WCF service method that can't deserialize the post in XML format and will error with

Error in line 14 position 30. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''

I narrow down to the specific section like the reproducible sample below

var xmlSrc = @"<Keys>
                  <ProductKeyID>123</ProductKeyID>
                  <ProductKeyID>124</ProductKeyID>
                  <ProductKeyID>125</ProductKeyID>
               </Keys>";
DataContractSerializer serializer = new DataContractSerializer(typeof(Keys));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSrc)))
{

    var i = (Keys)serializer.ReadObject(stream);
}

[DataContract(Namespace = "")]
[Serializable]
public class Keys
{
    [DataMember(Order = 1)]
    public List<string> ProductKeyID { get; set; }
}

How to adjust the C# class to deserialize the XML properly?

I do search the post exists but most of them are json format and do not seem to help my case.


Solution

  • As an alternative you can use CollectionDataContract attribute. Your class Keys will be inherited from List. In CollectionDataContract attribute specify name of the root element and name of items.

    [CollectionDataContract(Name = "Keys", ItemName = "ProductKeyID", Namespace ="")]
    public class Keys<T> : List<T>
    {
    }
    
    DataContractSerializer serializer = new DataContractSerializer(typeof(Keys<string>));
    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSrc)))
    {
        var i = (Keys<string>)serializer.ReadObject(stream);
    }