SORU
31 Temmuz 2009, Cuma


Seri hale getirilebilir genel liste XML nesneleri Getirmek

Kendi türünü belirtmek zorunda kalmadan seri hale getirilebilir nesneler genel liste seri hale getirmek.

Kırık kodu aşağıdaki arkasındaki niyeti gibi bir şey:

List<ISerializable> serializableList = new List<ISerializable>();

XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());

serializableList.Add((ISerializable)PersonList);

using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xmlSerializer.Serialize(streamWriter, serializableList);
}

Düzenleme:

Detay öğrenmek isteyenler için: bu kodu çalıştırmaya çalıştığımda, XMLSerializer hataları[...] doğrultusunda:

Edemez hale arabirimi Sistem.Çalışma zamanı.Seri hale getirme.Iserializable.

Eğer List<object> değiştirirsem "There was an error generating the XML document." olsun. InnerException detayı "{"The type System.Collections.Generic.List1[[Project1.Person, ConsoleFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context."}"

Kişi, nesne, aşağıdaki gibi tanımlanır

[XmlRoot("Person")]
public class Person
{
    string _firstName = String.Empty;
    string _lastName = String.Empty;

    private Person()
    {
    }

    public Person(string lastName, string firstName)
    {
        _lastName = lastName;
        _firstName = firstName;
    }

    [XmlAttribute(DataType = "string", AttributeName = "LastName")]
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    [XmlAttribute(DataType = "string", AttributeName = "FirstName")]
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
}

Bu PersonList List<Person> sadece bir .

Bu sadece test için olsa da, bu yüzden ayrıntılar çok önemli olduğunu hissetmedim. Anahtar seri hale getirilebilir hepsi bir ya da daha fazla farklı nesneler var. Hepsini tek bir dosyada onları seri hale getirmek istiyorum. Genel bir liste koydu ve bir liste seri hale getirmek için bunun en basit yolu düşündüm. Ama bu işe yaramıyor.

List<IXmlSerializable> ile de denedim, ama başarısız olur

System.Xml.Serialization.IXmlSerializable cannot be serialized because it does not have a parameterless constructor.

Detay eksikliği için özür dilerim, ama bu bir acemi olduğumu ve ayrıntılı nelerin gerekli olduğunu bilmiyorum. Eğer insanlar daha fazla ayrıntı için sorup cevap ayrıntılar gerekli, ya da temel bir cevap Olası yönleri özetleyen bana anlayış bırakacak bir şekilde çalıştı, faydalı olacaktır.

Ayrıcateşekkürleriki cevap için şimdiye kadar var - bu fikirleri almadan çok fazla zaman okuma harcayabilirdim. Yardımsever insanlar bu sitede ne kadar şaşırtıcı.

CEVAP
25 ŞUBAT 2011, Cuma


Genel Liste<^ a için bir çözüm buldum . dinamik bağlanmış öğeleri ile.

kök elemanı sınıf PersonalList

[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
    [XmlArray("PersonenArray")]
    [XmlArrayItem("PersonObjekt")]
    public List<Person> Persons = new List<Person>();

    [XmlElement("Listname")]
    public string Listname { get; set; }

    // Konstruktoren 
    public PersonalList() { }

    public PersonalList(string name)
    {
        this.Listname = name;
    }

    public void AddPerson(Person person)
    {
        Persons.Add(person);
    }
}

sınıf Kişi Listesi tek bir element

[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]  
        // include type class SpecialPerson and class SuperPerson
public class Person
{
    [XmlAttribute("PersID", DataType = "string")]
    public string ID { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("City")]
    public string City { get; set; }

    [XmlElement("Age")]
    public int Age { get; set; }

    // Konstruktoren 
    public Person() { }

    public Person(string name, string city, int age, string id)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
    }
}

sınıf SpecialPerson Kişi devralır

[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
    [XmlElement("SpecialInterests")]
    public string Interests { get; set; }

    public SpecialPerson() { }

    public SpecialPerson(string name, string city, int age, string id, string interests)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        this.Interests = interests;
    }
}

sınıf SuperPerson Kişi devralır

[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
    [XmlArray("Skills")]
    [XmlArrayItem("Skill")]
    public List<String> Skills { get; set; }

    [XmlElement("Alias")]
    public string Alias { get; set; }

    public SuperPerson() 
    {
        Skills = new List<String>();
    }

    public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
    {
        Skills = new List<String>();

        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        foreach (string item in skills)
        {
            this.Skills.Add(item);   
        }
        this.Alias = alias;
    }
}

ana test Kaynağı

static void Main(string[] args)
{
    PersonalList personen = new PersonalList(); 
    personen.Listname = "Friends";

    // normal person
    Person normPerson = new Person();
    normPerson.ID = "0";
    normPerson.Name = "Max Man";
    normPerson.City = "Capitol City";
    normPerson.Age = 33;

    // special person
    SpecialPerson specPerson = new SpecialPerson();
    specPerson.ID = "1";
    specPerson.Name = "Albert Einstein";
    specPerson.City = "Ulm";
    specPerson.Age = 36;
    specPerson.Interests = "Physics";

    // super person
    SuperPerson supPerson = new SuperPerson();
    supPerson.ID = "2";
    supPerson.Name = "Superman";
    supPerson.Alias = "Clark Kent";
    supPerson.City = "Metropolis";
    supPerson.Age = int.MaxValue;
    supPerson.Skills.Add("fly");
    supPerson.Skills.Add("strong");

    // Add Persons
    personen.AddPerson(normPerson);
    personen.AddPerson(specPerson);
    personen.AddPerson(supPerson);

    // Serialize 
    Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
    XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes); 
    FileStream fs = new FileStream("Personenliste.xml", FileMode.Create); 
    serializer.Serialize(fs, personen); 
    fs.Close(); 
    personen = null;

    // Deserialize 
    fs = new FileStream("Personenliste.xml", FileMode.Open); 
    personen = (PersonalList)serializer.Deserialize(fs); 
    serializer.Serialize(Console.Out, personen);
    Console.ReadLine();
}

Önemli olan farklı türleri tanımı ve içerir.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • metal571

    metal571

    30 Mayıs 2006
  • Truc Minh

    Truc Minh

    23 Ocak 2011
  • xSammyJoe1

    xSammyJoe1

    19 Temmuz 2011