3

Trying to Deserialise XML response to C#. but getting error as specified below.

My code:

IRestResponse result = Client.Execute<StudentPersonal>(new RestRequest(Method.POST)
    .AddHeader("Accept", " application/xml")
    .AddHeader("Authorization", "Basic Y2xaTWNqZFFlbFF4YVU1TlFtUnZOV3hXTkhadmNHaFhPSGxTT0Rka1VIcFhhRTl5TWtWQ05rRjNUMlp5VlUxWlNYa3hjbEU1V1RGUmMxTkNOMlZWVlRvNk9nPT06eUkxdERIanNVcGxLUUpzUlNXNTVacXpRVUFGQ3JrZzFwUGxUbDhUTmRQaFU0Z0xsTFJlQkVxTmhzZml3TnpaVA==")
    .AddHeader("Content-Type", "application/xml")
    .AddParameter("application/xml", body, ParameterType.RequestBody));

StudentPersonal firstResponse = new StudentPersonal();
StringReader srt = new StringReader(result.Content);
XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal), new XmlRootAttribute("StudentPersonal"));
firstResponse = (StudentPersonal)serializer.Deserialize(srt);
Console.WriteLine(firstResponse);
Assert.AreEqual("Created", result.StatusCode.ToString());

My classes:

[XmlRoot(ElementName = "StudentPersonal")]
public class StudentPersonal
{
    //// XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal));
    //// using (StringReader reader = new StringReader(xml))
    //// {
    ////    var test = (StudentPersonal)serializer.Deserialize(reader);
    //// }

    [XmlElement(ElementName = "LocalId")]
    public double LocalId { get; set; }

    [XmlElement(ElementName = "StateProvinceId")]
    public int StateProvinceId { get; set; }

    [XmlElement(ElementName = "ElectronicIdList")]
    public object ElectronicIdList { get; set; }

    [XmlElement(ElementName = "OtherIdList")]
    public OtherIdList OtherIdList { get; set; }

    [XmlElement(ElementName = "PersonInfo")]
    public PersonInfo PersonInfo { get; set; }

    [XmlElement(ElementName = "GiftedTalented")]
    public string GiftedTalented { get; set; }

    [XmlElement(ElementName = "EconomicDisadvantage")]
    public string EconomicDisadvantage { get; set; }

    [XmlElement(ElementName = "ESL")]
    public string ESL { get; set; }

    [XmlElement(ElementName = "YoungCarersRole")]
    public string YoungCarersRole { get; set; }

    [XmlElement(ElementName = "Disability")]
    public string Disability { get; set; }

    [XmlElement(ElementName = "IntegrationAide")]
    public string IntegrationAide { get; set; }

    [XmlElement(ElementName = "EducationSupport")]
    public string EducationSupport { get; set; }

    [XmlElement(ElementName = "Sensitive")]
    public string Sensitive { get; set; }

    [XmlAttribute(AttributeName = "xsd")]
    public string Xsd { get; set; }

    [XmlAttribute(AttributeName = "xsi")]
    public string Xsi { get; set; }

    [XmlAttribute(AttributeName = "RefId")]
    public string RefId { get; set; }

    [XmlAttribute(AttributeName = "xmlns")]
    public string Xmlns { get; set; }

    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "OtherId")]
public class OtherId
{
    [XmlAttribute(AttributeName = "Type")]
    public string Type { get; set; }

    [XmlText]
    public int Text { get; set; }
}

[XmlRoot(ElementName = "OtherIdList")]
public class OtherIdList
{
    [XmlElement(ElementName = "OtherId")]
    public List<OtherId> OtherId { get; set; }
}

[XmlRoot(ElementName = "Name")]
public class Name
{
    [XmlElement(ElementName = "Title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "FamilyName")]
    public string FamilyName { get; set; }

    [XmlElement(ElementName = "GivenName")]
    public string GivenName { get; set; }

    [XmlElement(ElementName = "MiddleName")]
    public string MiddleName { get; set; }

    [XmlElement(ElementName = "FamilyNameFirst")]
    public string FamilyNameFirst { get; set; }

    [XmlElement(ElementName = "PreferredFamilyName")]
    public string PreferredFamilyName { get; set; }

    [XmlElement(ElementName = "PreferredFamilyNameFirst")]
    public string PreferredFamilyNameFirst { get; set; }

    [XmlElement(ElementName = "PreferredGivenName")]
    public string PreferredGivenName { get; set; }

    [XmlElement(ElementName = "FullName")]
    public string FullName { get; set; }

    [XmlAttribute(AttributeName = "Type")]
    public string Type { get; set; }

    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "EnglishProficiency")]
public class EnglishProficiency
{

    [XmlElement(ElementName = "Code")]
    public int Code { get; set; }
}

[XmlRoot(ElementName = "Language")]
public class Language
{
    [XmlElement(ElementName = "Code")]
    public int Code { get; set; }

    [XmlElement(ElementName = "LanguageType")]
    public int LanguageType { get; set; }
}

[XmlRoot(ElementName = "LanguageList")]
public class LanguageList
{
    [XmlElement(ElementName = "Language")]
    public List<Language> Language { get; set; }
}

[XmlRoot(ElementName = "DwellingArrangement")]
public class DwellingArrangement
{
    [XmlElement(ElementName = "Code")]
    public int Code { get; set; }
}

[XmlRoot(ElementName = "Religion")]
public class Religion
{
    [XmlElement(ElementName = "Code")]
    public int Code { get; set; }
}

[XmlRoot(ElementName = "ReligiousEvent")]
public class ReligiousEvent
{
    [XmlElement(ElementName = "Type")]
    public string Type { get; set; }

    [XmlElement(ElementName = "Date")]
    public DateTime Date { get; set; }
}

[XmlRoot(ElementName = "ReligiousEventList")]
public class ReligiousEventList
{
    [XmlElement(ElementName = "ReligiousEvent")]
    public ReligiousEvent ReligiousEvent { get; set; }
}

[XmlRoot(ElementName = "Demographics")]
public class Demographics
{
    [XmlElement(ElementName = "IndigenousStatus")]
    public int IndigenousStatus { get; set; }

    [XmlElement(ElementName = "Sex")]
    public int Sex { get; set; }

    [XmlElement(ElementName = "BirthDate")]
    public DateTime BirthDate { get; set; }

    [XmlElement(ElementName = "BirthDateVerification")]
    public int BirthDateVerification { get; set; }

    [XmlElement(ElementName = "CountryArrivalDate")]
    public DateTime CountryArrivalDate { get; set; }

    [XmlElement(ElementName = "EnglishProficiency")]
    public EnglishProficiency EnglishProficiency { get; set; }

    [XmlElement(ElementName = "LanguageList")]
    public LanguageList LanguageList { get; set; }

    [XmlElement(ElementName = "DwellingArrangement")]
    public DwellingArrangement DwellingArrangement { get; set; }

    [XmlElement(ElementName = "Religion")]
    public Religion Religion { get; set; }

    [XmlElement(ElementName = "ReligiousEventList")]
    public ReligiousEventList ReligiousEventList { get; set; }

    [XmlElement(ElementName = "PermanentResident")]
    public string PermanentResident { get; set; }

    [XmlElement(ElementName = "VisaSubClass")]
    public int VisaSubClass { get; set; }

    [XmlElement(ElementName = "VisaStatisticalCode")]
    public string VisaStatisticalCode { get; set; }

    [XmlElement(ElementName = "VisaExpiryDate")]
    public DateTime VisaExpiryDate { get; set; }

    [XmlElement(ElementName = "LBOTE")]
    public string LBOTE { get; set; }

    [XmlElement(ElementName = "ImmunisationCertificateStatus")]
    public string ImmunisationCertificateStatus { get; set; }

    [XmlElement(ElementName = "CulturalBackground")]
    public int CulturalBackground { get; set; }

    [XmlElement(ElementName = "MaritalStatus")]
    public int MaritalStatus { get; set; }

    [XmlElement(ElementName = "MedicareNumber")]
    public int MedicareNumber { get; set; }
}

[XmlRoot(ElementName = "PhoneNumber")]
public class PhoneNumber
{
    [XmlElement(ElementName = "Number")]
    public int Number { get; set; }

    [XmlElement(ElementName = "ListedStatus")]
    public string ListedStatus { get; set; }

    [XmlAttribute(AttributeName = "Type")]
    public int Type { get; set; }

    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "PhoneNumberList")]
public class PhoneNumberList
{
    [XmlElement(ElementName = "PhoneNumber")]
    public PhoneNumber PhoneNumber { get; set; }
}

[XmlRoot(ElementName = "Email")]
public class Email
{
    [XmlAttribute(AttributeName = "Type")]
    public int Type { get; set; }

    [XmlText]
    public string Text { get; set; }
}

[XmlRoot(ElementName = "EmailList")]
public class EmailList
{
    [XmlElement(ElementName = "Email")]
    public List<Email> Email { get; set; }
}

[XmlRoot(ElementName = "PersonInfo")]
public class PersonInfo
{
    [XmlElement(ElementName = "Name")]
    public Name Name { get; set; }

    [XmlElement(ElementName = "Demographics")]
    public Demographics Demographics { get; set; }

    [XmlElement(ElementName = "AddressList")]
    public object AddressList { get; set; }

    [XmlElement(ElementName = "PhoneNumberList")]
    public PhoneNumberList PhoneNumberList { get; set; }

    [XmlElement(ElementName = "EmailList")]
    public EmailList EmailList { get; set; }
}

Below is the response XML details from Result.content:

<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
    <LocalId>2432717276450097998</LocalId>
    <StateProvinceId>674361</StateProvinceId>
    <ElectronicIdList />
    <OtherIdList>
        <OtherId Type=\"MazeKey\">674363</OtherId>
        <OtherId Type=\"VETUSI\">674362</OtherId>
        <OtherId Type=\"UPN\">674363</OtherId>
    </OtherIdList>
    <PersonInfo>
        <Name Type=\"LGL\">
            <Title>Ms</Title>
            <FamilyName>Gutteridge2</FamilyName>
            <GivenName>Ferdinanda2</GivenName>
            <MiddleName>Creamer1</MiddleName>
            <FamilyNameFirst>N</FamilyNameFirst>
            <PreferredFamilyName>Gutteridge</PreferredFamilyName>
            <PreferredFamilyNameFirst>N</PreferredFamilyNameFirst>
            <PreferredGivenName>Ferdinanda</PreferredGivenName>
            <FullName> Ferdinanda Gutteridge</FullName>
        </Name>
        <Demographics>
            <IndigenousStatus>1</IndigenousStatus>
            <Sex>2</Sex>
            <BirthDate>2006-03-21</BirthDate>
            <BirthDateVerification>1004</BirthDateVerification>
            <CountryArrivalDate>2008-09-17</CountryArrivalDate>
            <EnglishProficiency>
                <Code>1</Code>
            </EnglishProficiency>
            <LanguageList>
                <Language>
                    <Code>1201</Code>
                    <LanguageType>3</LanguageType>
                </Language>
                <Language>
                    <Code>4303</Code>
                    <LanguageType>1</LanguageType>
                </Language>
                <Language>
                    <Code>4303</Code>
                    <LanguageType>1</LanguageType>
                </Language>
            </LanguageList>
            <DwellingArrangement>
                <Code>1671</Code>
            </DwellingArrangement>
            <Religion>
                <Code>0002</Code>
            </Religion>
            <ReligiousEventList>
                <ReligiousEvent>
                    <Type>Confirmation</Type>
                    <Date>2018-07-17</Date>
                </ReligiousEvent>
            </ReligiousEventList>
            <PermanentResident>P</PermanentResident>
            <VisaSubClass>124</VisaSubClass>
            <VisaStatisticalCode>VisaStatisticalCode</VisaStatisticalCode>
            <VisaExpiryDate>2019-01-17</VisaExpiryDate>
            <LBOTE>N</LBOTE>
            <ImmunisationCertificateStatus>C</ImmunisationCertificateStatus>
            <CulturalBackground>0901</CulturalBackground>
            <MaritalStatus>3</MaritalStatus>
            <MedicareNumber>67436</MedicareNumber>
        </Demographics>
        <AddressList />
        <PhoneNumberList>
            <PhoneNumber Type=\"0350\">
                <Number>12367436</Number>
                <ListedStatus>U</ListedStatus>
            </PhoneNumber>
        </PhoneNumberList>
        <EmailList>
            <Email Type=\"01\">[email protected]</Email>
            <Email Type=\"02\">[email protected]</Email>
            <Email Type=\"03\">[email protected]</Email>
        </EmailList>
    </PersonInfo>
    <GiftedTalented>N</GiftedTalented>
    <EconomicDisadvantage>N</EconomicDisadvantage>
    <ESL>N</ESL>
    <YoungCarersRole>N</YoungCarersRole>
    <Disability>N</Disability>
    <IntegrationAide>N</IntegrationAide>
    <EducationSupport>U</EducationSupport>
    <Sensitive>N</Sensitive>
</StudentPersonal>

Error is from the above XML response. Getting Error

There is an error in XML document (1, 2). InvalidOperationException: <StudentPersonal xmlns='http://www.sifassociation.org/datamodel/au/3.4'> was not expected.
5
  • you should provide what resul.Content evaluates to when you execute that code. It's impossible for us to guess why an xml may be invalid if you don't provide that xml. Commented Nov 9, 2021 at 12:23
  • 1
    If the XML has a namespace, you have to add it to the XmlRoot attribute, too: [XmlRoot(ElementName = "StudentPersonal", Namespace = "http://www.sifassociation.org/datamodel/au/3.4")] Commented Nov 9, 2021 at 12:24
  • 1
    Looks like your StudentPersonal class doesn't specify that XML namespace? E.g. [XmlRoot(ElementName = "StudentPersonal", Namespace = "http://www.sifassociation.org/datamodel/au/3.4")]
    – canton7
    Commented Nov 9, 2021 at 12:24
  • Hmm - how do double quotes turn into single quotes here? Commented Nov 9, 2021 at 13:45
  • Added result.Content details
    – Tt tt
    Commented Nov 9, 2021 at 14:42

1 Answer 1

0

There seems to be two issues.

  1. Add the namespace to your class:
[XmlRoot(ElementName = "StudentPersonal", Namespace = "http://www.sifassociation.org/datamodel/au/3.4")]
public class StudentPersonal
          ...
  1. In the XML, all " are escaped with \.
<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
                ...
</StudentPersonal>

This also occurs in other places throughout the XML. Such as:

<PhoneNumber Type=\"0350\">

To resolve the issue, replace all occurrences of \" with ".

<StudentPersonal xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RefId="9ec476fd-09b5-4b2b-967a-fb80b207526e" xmlns="http://www.sifassociation.org/datamodel/au/3.4">
                ...
</StudentPersonal>

and

<PhoneNumber Type="0350">

Here's a method that can be used to deserialize the XML:

DeserializeXMLStringToObject:

public static T DeserializeXMLStringToObject<T>(string xmlData)
{
    T rObject = default(T);

    try
    {
        if (string.IsNullOrEmpty(xmlData))
        {
            return default(T);
        }

        //replace \" with "
        string xmlDataSanitized = xmlData.Replace("\\\"", "\"");

        using (System.IO.StringReader reader = new System.IO.StringReader(xmlDataSanitized))
        {
            //add the namespace to the class instead of adding it here
            //System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), "http://www.sifassociation.org/datamodel/au/3.4");
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            rObject = (T)serializer.Deserialize(reader);
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw ex;
    }

    return rObject;
}

Usage:

private StudentPersonal _studentPersonal = null;
                ...

_studentPersonal = DeserializeXMLStringToObject<StudentPersonal>(result.Content);

//for testing, display some of the data
//System.Diagnostics.Debug.WriteLine("LocalId: " + _studentPersonal.LocalId);
//System.Diagnostics.Debug.WriteLine("GivenName: " + _studentPersonal.PersonInfo.Name.GivenName);
4
  • even if I convert \" to " , the StringReader object will again add \" in the code.
    – Tt tt
    Commented Nov 10, 2021 at 8:54
  • @TusharPrajapati: I've updated the post. Commented Nov 10, 2021 at 15:42
  • Regarding the string escaping, I think that @TusharPrajapati was confused by Visual Studio that adds c# string escaping around strings when displaying them. To see the raw string without any "helpful" VS escaping, see Stop visual studio debug putting slash in string containing double quotes and Can the Visual Studio Debugger display strings unquoted/unescaped?.
    – dbc
    Commented Nov 11, 2021 at 2:55
  • You are correct. Visual studio Text Visualizer displays XML without \" while debugging. I just remove xmlns attributes and NameSpaces with below code and It is working fine. var test1 = Regex.Replace(result.Content, "((?<=<|<\\/)|(?<= ))[A-Za-z0-9]+:| xmlns(:[A-Za-z0-9]+)?=\".*?\"", "");
    – Tt tt
    Commented Nov 11, 2021 at 16:37

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.