将多个对象写入/读入Xml C#

时间:2014-05-25 19:36:43

标签: c# .net xml

我是Xml的新手,并编写了创建Xml的代码并将其读回。 但我希望在Xml结构中进行一些修改。

我不想要的是ArrayOfMovie标签,它将作为根选项卡出现。 但是当我在Xml中写入多个对象时,它会显示一个ArrayOfMovie标记。由于我必须维护类的结构,上层标签为Movie,然后是其细节,然后是其他电影。如果你告诉代码修改xml,请告诉程序也要读取新结构化的xml。

以下是该方案的代码:

// Movies class which contains the list of Movie objects
 public class Movies
    {
     public List<Movie> movieList = new List<Movie>();

    }

  //Movie class
  public class Movie
    {

        public string Title
        { get; set; }


        public int Rating
        { get; set; }


        public DateTime ReleaseDate
        { get; set; }

    }

    private void CreateXml_Click(object sender, EventArgs e)
    {
        string filePath = path + textBox_XmlFileName.Text+".xml";

        Movie firstMov = new Movie();
        firstMov.Title = "Shrek";
        firstMov.Rating = 2;
        firstMov.ReleaseDate = DateTime.Now;

        Movie secondMov = new Movie();
        secondMov.Title = "Spider Man";
        secondMov.Rating = 4;
        secondMov.ReleaseDate = DateTime.Now;

        Movies moviesObj = new Movies();
        moviesObj.movieList.Add(firstMov);
        moviesObj.movieList.Add(secondMov);
        List<Movie> movList = new List<Movie>() { firstMov,secondMov};

        XmlHandler.SerializeToXml(moviesObj.movieList, filePath);

    }

// The static class and funcion that creates the xml file 
       public static void SerializeToXml(List<Movie> movies ,string filePath)
       {
          XmlSerializer xls= new XmlSerializer(typeof(List<Movie>)); 

       TextWriter tw = new StreamWriter(filePath);
       xls.Serialize(tw, movies);
       tw.Close();
       }

// It创建以下输出

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Movie>
    <Title>Shrek</Title>
    <Rating>2</Rating>
    <ReleaseDate>2014-05-25T22:55:17.2811063+05:00</ReleaseDate>
  </Movie>
  <Movie>
    <Title>Spider Man</Title>
    <Rating>4</Rating>
    <ReleaseDate>2014-05-25T22:55:17.2811063+05:00</ReleaseDate>
  </Movie>
</ArrayOfMovie>

//将文件读入对象的代码

  public static List<Movie> DeserializeFromXml(string filePath)
   {
       XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
       TextReader tr = new StreamReader(@filePath);
       List<Movie> movie;
       movie = (List<Movie>)deserializer.Deserialize(tr);
       tr.Close();

       return movie;
   }

1 个答案:

答案 0 :(得分:1)

如果要命名根

,可以使用XmlRootAttribute
XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>), 
new XmlRootAttribute("YourRoot"));