【问题标题】:XmlSerializer.Deserialize issue with either root element missing or element not expectedXmlSerializer.Deserialize 问题与根元素丢失或元素不期望
【发布时间】:2010-09-16 14:25:38
【问题描述】:

我在反序列化 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 元素更改为也包含命名空间,那么我对根元素的错误更改将丢失。

我认为其中一个会给我预期的结果,但事实并非如此。有人可以发现我在这里缺少什么吗?

【问题讨论】:

    标签: c# xmlserializer


    【解决方案1】:

    我在反序列化时尝试正确修饰我的类时使用的一种方法是使用 XSD.exe 基于 XSD 生成 c# 类,然后将修饰与我自己的类进行比较。它不止一次阐明了问题。

    打开 Visual Studio 命令提示符,然后:

    xsd /c <filename>.xsd
    

    【讨论】:

    • XSD.exe 实际上是罪魁祸首!我是根据教程使用它的,起初没有做足够的阅读来理解它。问题肯定出在我的班级装饰员身上。我相信有 2 个根声明。它现在工作得很好。
    【解决方案2】:

    根据 XML 元素的命名空间设置 XmlRoot 属性的 Namespace 属性。

    它是 XML 文档的片段还是完整的? 我没有看到 XML 声明

    【讨论】:

    • 谢谢!这与我的问题直接相关。代码分为几个类,这种层次结构和这种 xml 响应的外观让我很困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多