Странная проблема десериализации

Я создал классы из схемы XSD, используя xsd.exe (также пробовал с xsd2code, который дал лучшие результаты, так как они работали сразу, а с xsd.exe я должен отладить некоторые ошибки). Схему XSD, которую я использовал, можно найти по адресу http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd, а образец файла - по адресу http://landxml.org/schema/LandXML-1.1/samples/AASHTO%20SDMS/MntnRoad.xml.

Мой код для десериализации выглядит так:

var mySerializer = new XmlSerializer(typeof (LandXML), new XmlRootAttribute(""));
TextReader myFileStream = new StreamReader("myFile.xml");
var myObject = (LandXML) mySerializer.Deserialize(myFileStream);

Моя проблема в том, что результатом десериализации является список элементов типа XmlElement, поэтому, если я попытаюсь получить доступ к их свойствам, я не смогу легко это сделать. Если я хочу получить доступ, например, к некоторому атрибуту объекта Alignment в myFile.xml, код будет похож на этот:

 var a = myObject.Items[5];
 var b = (XmlElement) a;
 var c = b.ChildNodes.Item(5).ChildNodes.Item(0).ChildNodes.Item(0).Attributes[0].Value;

Очевидно, что это не тот способ, который предназначен для десериализации XML в классах. Моя идея была такой (для того же элемента):

var c = LandXML.Alignments.Alignment.CoordGeometry.Curve.rot

Я не знаю, что я делаю неправильно, я пробовал с более простыми схемами, и этот код работал хорошо. Пожалуйста, помогите и tnx заранее!

РЕДАКТИРОВАТЬ 1

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

public class LandXML
    {

        private List<object> _items;

        private System.DateTime _date;

        private System.DateTime _time;

        private string _version;

        private string _language;

        private bool _readOnly;

        private int _landXMLId;

        private string _crc;

        public LandXML()
        {
            this._items = new List<object>();
        }

        [System.Xml.Serialization.XmlAnyElementAttribute()]
        [System.Xml.Serialization.XmlElementAttribute("Alignments", typeof(Alignments))]
        [System.Xml.Serialization.XmlElementAttribute("Amendment", typeof(Amendment))]
        [System.Xml.Serialization.XmlElementAttribute("Application", typeof(Application))]
        [System.Xml.Serialization.XmlElementAttribute("CgPoints", typeof(CgPoints))]
        [System.Xml.Serialization.XmlElementAttribute("CoordinateSystem", typeof(CoordinateSystem))]
        [System.Xml.Serialization.XmlElementAttribute("FeatureDictionary", typeof(FeatureDictionary))]
        [System.Xml.Serialization.XmlElementAttribute("GradeModel", typeof(GradeModel))]
        [System.Xml.Serialization.XmlElementAttribute("Monuments", typeof(Monuments))]
        [System.Xml.Serialization.XmlElementAttribute("Parcels", typeof(Parcels))]
        [System.Xml.Serialization.XmlElementAttribute("PipeNetworks", typeof(PipeNetworks))]
        [System.Xml.Serialization.XmlElementAttribute("PlanFeatures", typeof(PlanFeatures))]
        [System.Xml.Serialization.XmlElementAttribute("Project", typeof(Project))]
        [System.Xml.Serialization.XmlElementAttribute("Roadways", typeof(Roadways))]
        [System.Xml.Serialization.XmlElementAttribute("Surfaces", typeof(Surfaces))]
        [System.Xml.Serialization.XmlElementAttribute("Survey", typeof(Survey))]
        [System.Xml.Serialization.XmlElementAttribute("Units", typeof(Units))]
        public List<object> Items
        {
            get
            {
                return this._items;
            }
            set
            {
                this._items = value;
            }
        }

1 ответ

Попробуй это

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlSerializer xs = new XmlSerializer(typeof(LandXML));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            reader.Namespaces = false;
            LandXML landXML = (LandXML)xs.Deserialize(reader);
        }
    }

    [XmlRoot("LandXML")]
    public class LandXML
    {
        [XmlAttribute("version")]
        public double version  { get;set; }

        [XmlAttribute("date")]
        public DateTime date  { get;set; }

        [XmlAttribute("time")]
        public DateTime time { get; set; }

        [XmlAttribute("readOnly")]
        public Boolean readOnly  { get;set; }

        [XmlAttribute("language")]
        public string language  { get;set; }

        [XmlElement("Project")]
        public Project project { get; set; } 

        [XmlElement("Units")]
        public Units units { get; set; } 

        [XmlElement("Application")]
        public Application application { get; set; } 

        [XmlElement("Alignments")]
        public Alignments alignments { get; set; } 
}
    [XmlRoot("Project")]
    public class Project
    {
        [XmlAttribute("name")]
        public string name;
    }
    [XmlRoot("Units")]
    public class Units
    {
        [XmlElement("Imperial")]
        public Imperial imperial { get; set; } 
    }
    [XmlRoot("Application")]
    public class Application
    {
        [XmlElement("Author")]
        public Author author { get; set; } 
    }
    [XmlRoot("Imperial")]
    public class Imperial
    {
        [XmlAttribute("linearUnit")]
        public string linearUnit;

        [XmlAttribute("areaUnit")]
        public string areaUnit;

        [XmlAttribute("volumeUnit")]
        public string volumeUnit;

        [XmlAttribute("temperatureUnit")]
        public string temperaturUnit;

        [XmlAttribute("pressureUnit")]
        public string pressureUnit;

        [XmlAttribute("angularUnit")]
        public string angularUnit;

        [XmlAttribute("directionUnit")]
        public string name;
    }

    [XmlRoot("Author")]
    public class Author
    {
        [XmlAttribute("createdBy")]
        public string createdBy;

        [XmlAttribute("createdByEmail")]
        public string createdByEmail;

        [XmlAttribute("company")]
        public string company;

        [XmlAttribute("companyURL")]
        public string companyURL;

    }
    [XmlRoot("Alignments")]
    public class Alignments
    {
        [XmlAttribute("desc")]
        public string desc;

        [XmlElement("Alignment")]
        public Alignment alignment { get; set; } 

    }

    [XmlRoot("Alignment")]
    public class Alignment
    {
        [XmlAttribute("name")]
        public string name;

        [XmlAttribute("desc")]
        public string desc;

        [XmlAttribute("length")]
        public string length;

        [XmlAttribute("staStart")]
        public string staStart;

        [XmlElement("AlignPIs")]
        public AlignPIs alignPIs { get; set; } 
    }
    [XmlRoot("AlignPIs")]
    public class AlignPIs
    {
        [XmlElement("AlignPI")]
        public List<AlignPI> alignPI { get; set; } 
    }

    [XmlRoot("AlignPI")]
    public class AlignPI
    {
        [XmlElement("PI")]
        public PI pi { get; set; } 

        [XmlElement("InSpiral")]
        public InSpiral inSpiral { get; set; } 

        [XmlElement("Curve1")]
        public Curve1 cureve1 { get; set; } 

        [XmlElement("OutSpiral")]
        public OutSpiral outSpiral { get; set; } 

        [XmlElement("Station")]
        public Station station { get; set; } 
    }

    [XmlRoot("Station")]
    public class Station
    {
        [XmlText]
        public string value { get; set; }
    }


    [XmlRoot("PI")]
    public class PI
    {
        [XmlAttribute("code")]
        public int code;

        [XmlAttribute("name")]
        public int name;

        [XmlText]
        public string value;
    }

    [XmlRoot("InSpiral")]
    public class InSpiral
    {
        [XmlElement("Spiral")]
        public Spiral spiral { get; set; } 

    }

    [XmlRoot("Spiral")]
    public class Spiral
    {
        [XmlAttribute("length")]
        public double length;

        [XmlAttribute("radiusEnd")]
        public double radiusEnd;

        [XmlAttribute("radiusStart")]
        public double radiusStart;

        [XmlAttribute("rot")]
        public string rot;

        [XmlAttribute("spiType")]
        public string spiType;
    }

    [XmlRoot("Curve1")]
    public class Curve1
    {
        [XmlElement("Curve")]
        public Curve curve { get; set; } 
    }

    [XmlRoot("Curve")]
    public class Curve
    {
        [XmlAttribute("rot")]
        public string rot;

        [XmlAttribute("radius")]
        public double radius;
    }
    [XmlRoot("OutSpiral")]
    public class OutSpiral
    {
        [XmlElement("Spiral")]
        public Spiral spiral { get; set; } 
    }
}
Другие вопросы по тегам