简体   繁体   中英

Deserialization of xml to list of object

Im having a problem deserializing my xml file to a list of objects. The error that appears is "System.InvalidOperationException: "There is an error in XML document (2,2). InvalidOperationException <Feed xmlns="> was not expected. There seems to be something wrong when the conversion of xml to objects take place.

The program seems to break at: 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>();
            }
        }

My xml file:

<?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>

You need to start by defining types which model your XML. I generated these by copying your XML and then going to Edit -> Paste Special -> Paste XML As Classes in Visual Studio (and tidying up the results by hand), but you can also write them by hand (using this document and specifically this section as reference) or use 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; }
}

Then you can:

var serializer = new XmlSerializer(typeof(Feed));
var feed = (Feed)serializer.Deserialize(fs);

You have to define type of the object that System.Xml.Serialization.XmlSerializer can serialize. Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM