0

Возникли проблемы при десериализации списка. Есть два PropertyGrid с классами Tube и Intersection с наследниками, в каждом из которых хранятся различные конфигурации разных классов. И всё это должно сохранятся в одном xml файле, известно только что значение PropertyGrid Tube должно быть выбрано один раз а вот значений PropertyGrid Intersection может быть несколько. Вот код который сохраняет все значения, проверка осуществляется через foreach:

public bool Save(Tube m_tube, Intersection m_intersection, string m_fileName)
    {
        var settings = new XmlWriterSettings { Indent = true };
        using (var writer = XmlWriter.Create(m_fileName, settings))
        {
            writer.WriteStartElement("Part");

            var ser = new XmlSerializer(typeof(Tube));
            ser.Serialize(writer, m_tube);

            foreach (IntersectionListItem de in MainViewModel.GetInstance().IntersectionView._IntersectionRepository._Intersections)
            {
                ser = new XmlSerializer(typeof(Intersection));
                ser.Serialize(writer, (Intersection)de._Intersection);
            }

            writer.WriteEndElement();
        }

        return true;
    }

Файл отлично создаётся. А вот как теперь осуществить десериализация через цикл? Вот файл который создался, были выбраны один из наследников класса Tube и три наследника класса Intersection

<?xml version="1.0" encoding="utf-8"?>
<Part>
  <Tube xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="OvalTube">
    <Type>OvalTube</Type>
    <WallThickness>25</WallThickness>
    <Height>25</Height>
    <Width>25</Width>
  </Tube>
  <Intersection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="PlaneIntersection">
    <Type>PlaneIntersection</Type>
    <Position>Middle</Position>
    <Cut>InnerCut</Cut>
    <Movement>Robot</Movement>
    <Burning>Marking</Burning>
  </Intersection>
  <Intersection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="TubeIntersection">
    <Type>TubeIntersection</Type>
    <Position>Left</Position>
    <Cut>OuterCut</Cut>
    <Movement>RotationAxis</Movement>
    <Burning>Cutting</Burning>
    <_TubeDiameter>0</_TubeDiameter>
  </Intersection>
  <Intersection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ConeIntersection">
    <Type>ConeIntersection</Type>
    <Position>Left</Position>
    <Cut>InnerCut</Cut>
    <Movement>Robot</Movement>
    <Burning>Cutting</Burning>
  </Intersection>
</Part>

Пробовала через цикл но не получается:

public bool Load(string m_fileName)
    {
        using (var reader = XmlReader.Create(m_fileName))
        {
            reader.ReadToFollowing("Tube");

            var ser = new XmlSerializer(typeof(Tube));
            MainViewModel.GetInstance().PartView._Tube = (Tube)ser.Deserialize(reader);

            ser = new XmlSerializer(typeof(Intersection));
            MainViewModel.GetInstance().IntersectionView._Intersection = (Intersection)ser.Deserialize(reader);

            foreach (IntersectionListItem inter in MainViewModel.GetInstance().IntersectionView._IntersectionRepository._Intersections)
                MainViewModel.GetInstance().IntersectionView._IntersectionRepository.AddIntersection(inter);
        }

        return true;
    }

Так читается только Tube и первый созданный Intersection.

1 ответ 1

1
MainViewModel.GetInstance().IntersectionView._Intersection = (Intersection)ser.Deserialize(reader);

        foreach (IntersectionListItem inter in MainViewModel.GetInstance().IntersectionView._IntersectionRepository._Intersections)
            MainViewModel.GetInstance().IntersectionView._IntersectionRepository.AddIntersection(inter);

Сначала ты десериализируешь один Intersection и сохраняешь его в IntersectionView._Intersection, а потом пытаешься пройти циклом по списку IntersectionView._IntersectionRepository._Intersections. Очевидно, что этот список оказывается пустым, и в итоге ты получаешь единственный десериализированный Intersection.

Вообще с таким codestyle ошибки делаются легко и непринужденно, перепиши скорее.

2
  • А как? Может быть есть идеи? Уже несколько раз переписывала этот метод и никак не получается при десериализации сохранить в список. 5 дек 2012 в 13:08
  • while (serializer.CanDeserialize(reader)) { myIntersectionList.Add((Intersection)serializer.Deserialize(reader)); } 5 дек 2012 в 13:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.