XmlSerializer.Deserialize проблема с отсутствующим корневым элементом или непредвиденным элементом - PullRequest
0 голосов
/ 16 сентября 2010

У меня возникли проблемы с десериализацией XML-документа.Документ, который я пытаюсь десериализовать, таков:

<slt:CreateGiftRegistryResponse xmlns:slt="http://WWW.example.com/">
<slt:Response>
<slt:ResponseCode>ERROR</slt:ResponseCode>
<slt:ResponseDescription>Request unsuccessfull null</slt:ResponseDescription>
</slt:Response></slt:CreateGiftRegistryResponse>

Мой класс выглядит так:

/// <summary>
/// response to attempt to add items to a registry
/// </summary>
[XmlRoot("CreateGiftRegistryResponse")]
public class CreateRegistryResponse : ResponseBase
{
    // Constant Declarations

    // Variable Declarations

    #region --- Constructors ---

    public CreateRegistryResponse()
        : this(String.Empty) { }

    /// <summary>
    /// response to attempt to add items to a registry
    /// </summary>
    /// <param name="response">xml string</param>
    public CreateRegistryResponse(string responseXml)
    {
        try
        {
            Load(responseXml);
        }
        catch (Exception ex)
        {
            // Report the exception and throw to the caller for handling.
            ExceptionManager.Publish(ex,
                "ctor CreateRegistryResponse() failed.",
                Severity.Fatal);
            throw;
        }
    }
    #endregion

    #region --- Properties ---
    /// <summary>
    /// structure for the typical response - code and description
    /// </summary>
    [XmlElement("Response")]
    public ResponseWS Response { get; set; }


    #endregion

    #region --- Static Methods ---
    #endregion

    #region --- CRUD ---
    #endregion

    #region --- Validation ---
    #endregion

    #region --- Business Methods ---
    /// <summary>
    /// Load the web service result string into a Result.
    /// </summary>
    public void Load(string response)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(CreateRegistryResponse), this.GetExtraTypes());
            byte[] byteArray = Encoding.ASCII.GetBytes(response);
            MemoryStream stream = new MemoryStream(byteArray);

            // convert the results into a usable format
            CreateRegistryResponse formattedResponse = serializer.Deserialize(stream) as CreateRegistryResponse;

            this.Response = formattedResponse.Response;
            if (formattedResponse.Response.ResponseCode == ResponseCode.SUCCESS.ToString())
            {
                this.IsSuccessful = true;
            }


        }
        catch (Exception ex)
        {
            // Report the exception and throw to the caller for handling.
            ExceptionManager.Publish(ex,
                "Load() failed. Unable to authenticate user.",
                Severity.Fatal);
            throw;
        }
        finally
        {
            //
            // TODO: Add clean-up code here, if needed.
            //
        }
    }

    /// <summary>
    /// Get an array of types that are possibly contained within this class
    /// </summary>
    public Type[] GetExtraTypes()
    {
        try
        {
            //
            // TODO: Add code here.
            //
            // build an array of possible types within this type.
            List<Type> types = new List<Type>();
            types.Add(typeof(ResponseWS));


            return types.ToArray();


        }
        catch (Exception ex)
        {
            // Report the exception and throw to the caller for handling.
            ExceptionManager.Publish(ex,
                "GetExtraTypes() failed. Unable to return list",
                Severity.Fatal);
            throw;
        }
    }
    #endregion
}

Когда я использую этот код, я получаю эту ошибку: {"http://kiosk.surlatable.com/'>не ожидалось. "}

Если я изменю элемент XmlRoot, чтобы он также содержал пространство имен, то моя ошибка при изменении корневого элемента отсутствует.

Я думал, что один из них даст мне ожидаемый результат, но это не так.Может кто-то определить, что мне здесь не хватает?

Ответы [ 2 ]

3 голосов
/ 16 сентября 2010

Подход, который я использовал, пытаясь правильно оформить свои классы при десериализации, - это использовать XSD.exe для генерации классов c # на основе XSD, а затем сравнить оформление с моим собственным классом. В более чем одном случае это пролило свет на проблемы.

Откройте командную строку Visual Studio, затем:

xsd /c <filename>.xsd
1 голос
/ 16 сентября 2010

Установите свойство Namespace вашего атрибута XmlRoot в соответствии с пространством имен элемента XML.

Это фрагмент документа XML или полный?Я не вижу декларации XML

...