Я пытаюсь взять строку XML, десериализовать ее и привязать к моему классу модели. Но я получаю эту ошибку:

System.InvalidOperationException: <requisitions xmlns=''> не ожидалось

Это C #, где я вызываю десериализацию:

var deserializer = new XmlSerializer(typeof(JobsModel),new XmlRootAttribute("requisition"));
var jobs = new JobsModel();

using (var reader = new StringReader(xmlStr))
{
    jobs = (JobsModel)deserializer.Deserialize(reader);
}

Мой XML отформатирован так:

<requisitions>
    <requisition>
        <start_date></start_date>
        <end_date></end_date>
        <title></title>
        <precise_location>
            <address1/>
            <city></city>
            <display_city/>
            <country></country>
        </precise_location>
        <contract_type></contract_type>
        <experience></experience>
        <job_type></job_type>
    </requisition>
    <requisition>
        <start_date></start_date>
        <end_date></end_date>
        <title></title>
        <precise_location>
            <address1/>
            <city></city>
            <display_city/>
            <country></country>
        </precise_location>
        <contract_type></contract_type>
        <experience></experience>
        <job_type></job_type>
    </requisition>
</requisitions>

И класс, который я пытаюсь десериализовать, таков:

public class JobsModel
{
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(IsNullable = false)]
    public partial class requisition
    {
        [System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
        public System.DateTime start_date { get; set; }

        [System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
        public System.DateTime end_date { get; set; }

        public string title { get; set; }
        public requisitionPrecise_location precise_location { get; set; }
        public string contract_type { get; set; }
        public object experience { get; set; }
        public object job_type { get; set; }
    }

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class requisitionPrecise_location
    {
        public object address1 { get; set; }
        public string city { get; set; }
        public object display_city { get; set; }
        public string country { get; set; }
    }
}

Решение

Я использовал функцию Visual Studio Paste Special для создания моделей. Но где я ошибся, так это в том, что XML, который я скопировал в буфер обмена, содержал только один элемент Requisition. Таким образом, Visual Studio не сгенерировала класс так, как мне было нужно, если у меня будет несколько запросов.

-1
KidBilly 12 Фев 2021 в 00:34

1 ответ

Лучший ответ

Вам не следует изменять сгенерированные классы. Вы можете переименовать корневой объект, если хотите. Но внесите небольшие изменения, проверяя каждую из них. Специальная вставка + десериализация работает, как и ожидалось, с этим XML для начала. НАПРИМЕР

using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApp24
{

    // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class requisitions
    {

        private requisitionsRequisition[] requisitionField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("requisition")]
        public requisitionsRequisition[] requisition
        {
            get
            {
                return this.requisitionField;
            }
            set
            {
                this.requisitionField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class requisitionsRequisition
    {

        private object start_dateField;

        private object end_dateField;

        private object titleField;

        private requisitionsRequisitionPrecise_location precise_locationField;

        private object contract_typeField;

        private object experienceField;

        private object job_typeField;

        /// <remarks/>
        public object start_date
        {
            get
            {
                return this.start_dateField;
            }
            set
            {
                this.start_dateField = value;
            }
        }

        /// <remarks/>
        public object end_date
        {
            get
            {
                return this.end_dateField;
            }
            set
            {
                this.end_dateField = value;
            }
        }

        /// <remarks/>
        public object title
        {
            get
            {
                return this.titleField;
            }
            set
            {
                this.titleField = value;
            }
        }

        /// <remarks/>
        public requisitionsRequisitionPrecise_location precise_location
        {
            get
            {
                return this.precise_locationField;
            }
            set
            {
                this.precise_locationField = value;
            }
        }

        /// <remarks/>
        public object contract_type
        {
            get
            {
                return this.contract_typeField;
            }
            set
            {
                this.contract_typeField = value;
            }
        }

        /// <remarks/>
        public object experience
        {
            get
            {
                return this.experienceField;
            }
            set
            {
                this.experienceField = value;
            }
        }

        /// <remarks/>
        public object job_type
        {
            get
            {
                return this.job_typeField;
            }
            set
            {
                this.job_typeField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class requisitionsRequisitionPrecise_location
    {

        private object address1Field;

        private object cityField;

        private object display_cityField;

        private object countryField;

        /// <remarks/>
        public object address1
        {
            get
            {
                return this.address1Field;
            }
            set
            {
                this.address1Field = value;
            }
        }

        /// <remarks/>
        public object city
        {
            get
            {
                return this.cityField;
            }
            set
            {
                this.cityField = value;
            }
        }

        /// <remarks/>
        public object display_city
        {
            get
            {
                return this.display_cityField;
            }
            set
            {
                this.display_cityField = value;
            }
        }

        /// <remarks/>
        public object country
        {
            get
            {
                return this.countryField;
            }
            set
            {
                this.countryField = value;
            }
        }
    }


    class Program
    {

        static void Main(string[] args)
        {
            var xml = @"<requisitions>
    <requisition>
        <start_date></start_date>
        <end_date></end_date>
        <title></title>
        <precise_location>
            <address1/>
            <city></city>
            <display_city/>
            <country></country>
        </precise_location>
        <contract_type></contract_type>
        <experience></experience>
        <job_type></job_type>
    </requisition>
    <requisition>
        <start_date></start_date>
        <end_date></end_date>
        <title></title>
        <precise_location>
            <address1/>
            <city></city>
            <display_city/>
            <country></country>
        </precise_location>
        <contract_type></contract_type>
        <experience></experience>
        <job_type></job_type>
    </requisition>
</requisitions>
";
            using (var reader = new StringReader(xml))
            {
                var deserializer = new XmlSerializer(typeof(requisitions), new XmlRootAttribute("requisitions"));

                var r = (requisitions)deserializer.Deserialize(reader);
            }
            Console.WriteLine("Hello World!");
        }
    }
}
1
David Browne - Microsoft 11 Фев 2021 в 22:08