Десериализация xml в список объектов - PullRequest
0 голосов
/ 24 октября 2019

У меня возникла проблема с десериализацией моего xml-файла в список объектов. Появляется ошибка «System.InvalidOperationException:» В документе XML есть ошибка (2,2). InvalidOperationException <Feed xmlns="> не ожидалось. Кажется, что-то не так, когда происходит преобразование xml в объекты.

Программа, кажется, ломается в: list = (List<object>) loadXML.Deserialize(fs);

public static List<object> deSerialize()
        {

            string path = Environment.CurrentDirectory + "\\xmlfile.xml";
            XmlSerializer loadXML = new XmlSerializer(typeof(List<object>));

            List<object> list = new List<object>();
            if (File.Exists(path))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    list = (List<object>) loadXML.Deserialize(fs);

                    //var lista = (List<object>)obj;

                    return list;
                }
            }
            else
            {
                return new List<object>();
            }
        }

Мой xml файл:

<?xml version="1.0"?>
<Feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>NASA Breaking News</Name>
  <NumberOfEpisodes>10</NumberOfEpisodes>
  <Episodes>
    <Episode>
      <EpisodeNumber>1</EpisodeNumber>
      <Title>NASA Invites Media to Next SpaceX Space Station Cargo Launch</Title>
      <Description>Media accreditation is open for the launch of the next SpaceX delivery of science investigations, supplies, and equipment to the International Space Station.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>2</EpisodeNumber>
      <Title>NASA Administrator Invites Public to Update on Agency’s Return to Moon</Title>
      <Description>The public is invited to join NASA Administrator Jim Bridenstine at 9:40 a.m. EDT Friday, Oct. 25, for an update on the agency’s Artemis program and the critical role international partnerships have in returning astronauts to the Moon and going on to Mars.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>3</EpisodeNumber>
      <Title>Maryland, Washington Students to Speak with NASA Astronaut Aboard Space Station</Title>
      <Description>Students from Maryland and Washington, D.C., will have an opportunity this week to talk with a NASA astronaut currently living and working aboard the International Space Station.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>4</EpisodeNumber>
      <Title>NASA Invites Media to Boeing Starliner Transport to Launch Site</Title>
      <Description>Media accreditation is open for two-days of activities in mid-November for the next milestone in NASA’s Commercial Crew Program, as Boeing’s CST-100 Starliner is transported for integration on a United Launch Alliance (ULA) Atlas V rocket.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>5</EpisodeNumber>
      <Title>NASA to Provide Coverage of Key Events at 70th International Astronautical Congress</Title>
      <Description>NASA will provide live coverage on NASA Television of key events at the 70th International Astronautical Congress (IAC), which takes place Oct. 21-25 at the Walter E. Washington Convention Center in Washington.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>6</EpisodeNumber>
      <Title>In-Space News Conference to Review First All-Woman Spacewalk</Title>
      <Description>NASA astronauts Christina Koch and Jessica Meir will participate in a news conference from orbit at noon EDT, Monday, Oct. 21, following their Friday spacewalk – the first to be conducted by two women.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>7</EpisodeNumber>
      <Title>NASA’s Planetary Protection Review Addresses Changing Reality of Space Exploration</Title>
      <Description>NASA released a report Friday with recommendations from the Planetary Protection Independent Review Board (PPIRB) the agency established in response to a recent National Academies of Sciences, Engineering, and Medicine report and a recommendation from the NASA Advisory Council.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>8</EpisodeNumber>
      <Title>NASA to Televise First All-Female Spacewalk, Host Media Teleconference</Title>
      <Description>On the first ever all-female spacewalk, NASA astronauts Christina Koch and Jessica Meir will venture outside the International Space Station about 7:50 a.m. EDT Friday, Oct. 18, to replace faulty equipment on the station’s exterior. Live coverage will begin at 6:30 a.m. on NASA Television and the agency’s website.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>9</EpisodeNumber>
      <Title>NASA Invites Media to Launch of Solar Orbiter Spacecraft</Title>
      <Description>NASA has opened media accreditation for the Feb. 5, 2020, launch of Solar Orbiter – a joint NASA/ESA (European Space Agency) mission that will address central questions concerning our star, the Sun.</Description>
    </Episode>
    <Episode>
      <EpisodeNumber>10</EpisodeNumber>
      <Title>NASA to Discuss Planetary Protection Review’s Findings and Recommendations</Title>
      <Description>NASA will host a media teleconference at 3:30 p.m. EDT Friday, Oct. 18, to discuss recommendations presented by the Planetary Protection Independent Review Board (PPIRB), established in June 2019 by Thomas Zurbuchen, associate administrator for the agency’s Science Mission Directorate.</Description>
    </Episode>
  </Episodes>
</Feed>

Ответы [ 2 ]

1 голос
/ 24 октября 2019

Вам нужно начать с определения типов, которые моделируют ваш XML. Я сгенерировал их, скопировав ваш XML и затем выбрав «Правка» -> «Специальная вставка» -> «Вставить XML как классы» в Visual Studio (и приведя результаты в порядок вручную), но вы также можете написать их вручную (используя этот документ и, в частности, этот раздел в качестве ссылки) или используйте xsd.exe.

public class Feed
{
    public string Name { get; set; }

    public byte NumberOfEpisodes { get; set; }

    [XmlArrayItem("Episode")]
    public List<Episode> Episodes { get; set; }
}

public class Episode
{
    public byte EpisodeNumber { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }
}

Тогда вы можете:

var serializer = new XmlSerializer(typeof(Feed));
var feed = (Feed)serializer.Deserialize(fs);
0 голосов
/ 24 октября 2019

Вы должны определить тип объекта, который System.Xml.Serialization.XmlSerializer может сериализовать. Пример:

var xs = new XmlSerializer(typeof(MyType));
return (MyType)xs.Deserialize(new StringReader(myXmlString));
...