Подтвердить что ты не робот

С# В документе XML есть ошибка (2, 2)

Я пытаюсь десериализовать следующий XML:

<?xml version="1.0" encoding="UTF-8"?>
<XGResponse><Failure code="400">
    Message id &apos;1&apos; was already submitted.
</Failure></XGResponse>

через этот вызов:

[...]
    var x = SerializationHelper.Deserialize<XMLGateResponse.XGResponse>(nResp);
[...]        

public static T Deserialize<T>(string xml)
{
    using (var str = new StringReader(xml))
    {
        var xmlSerializer = new XmlSerializer(typeof(T));
        return (T)xmlSerializer.Deserialize(str);
    }
}

чтобы получить экземпляр соответствующего класса:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18052
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 

namespace XMLGateResponse
{

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)]
    public partial class XGResponse
    {

        private object[] itemsField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("Failure", typeof(Failure))]
        [System.Xml.Serialization.XmlElementAttribute("Success", typeof(Success))]
        public object[] Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)]
    public partial class Failure
    {

        private string codeField;

        private string titleField;

        private string valueField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute(DataType = "NMTOKEN")]
        public string code
        {
            get
            {
                return this.codeField;
            }
            set
            {
                this.codeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string title
        {
            get
            {
                return this.titleField;
            }
            set
            {
                this.titleField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)]
    public partial class Success
    {

        private string titleField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string title
        {
            get
            {
                return this.titleField;
            }
            set
            {
                this.titleField = value;
            }
        }
    }
}

Но он вызывает ошибку There is an error in XML document (2, 2).
Я искал решение для этого около часа, но это мало помогло.

Я даже попробовал небольшое изменение, которое ничего не должно делать:

public static T Deserialize<T>(string xml)
{
    [...]
        var xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(typeof(T).Name));
    [...]
}

Тем не менее, это предотвращает ошибку. Но так как это только для того, чтобы вернуть мне экземпляр XMLGateResponse.XGResponse полностью пустым (все элементы/атрибуты равны нулю), это не действительно улучшение.

Я знаю, что такой вопрос There is an error in XML document (2, 2) уже обсуждался много, но я действительно не нашел решения, которое сработало для меня.

4b9b3361

Ответ 1

XGResponse украшен XmlRootAttribute, который указывает имя namspace по умолчанию, но ваш документ не работает.

Либо удалите это объявление пространства имен, либо добавьте xmlns="http://tempuri.org/XMLGateResponse" в корневой элемент xml

Ответ 2

Если вы попытаетесь десериализовать неправильный тип, вы можете получить ту же ошибку.
Например, если вы вызываете

Deserialize<object>(myXml)

или

Deserialize<Failure>(myXml)

Я знаю, что это плохая практика, чтобы ответить на Q, когда 1) ответ уже предоставлен и 2) ответ не совсем то, о чем спрашивал вопрошающий; но я думаю, что это может сэкономить некоторое время для того, чтобы кто-то другой нашел свой путь здесь с проблемой, не такой, как у испытуемого.