首页 > 代码库 > C#写入对象到XML/从XML读取对象

C#写入对象到XML/从XML读取对象

1.将一个sentenceresult对象写入xml,并保存

 private void writeToXml(sentenceresult sr) {

            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(sentenceresult));

            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//SerializationOverview.xml";
            System.IO.FileStream file = System.IO.File.Create(path);

            writer.Serialize(file, sr);
            file.Close(); 
        
        }

注意:sentenceresult 必须要有无参构造函数,而且其成员变量必须要是public

2.从一个xml文件读取sentenceresult对象

   private sentenceresult writeToXml(String path)
        {

            System.Xml.Serialization.XmlSerializer reader =
                  new System.Xml.Serialization.XmlSerializer(typeof(sentenceresult));
            System.IO.StreamReader file = new System.IO.StreamReader(path);
            sentenceresult result = new sentenceresult();
            result = (sentenceresult)reader.Deserialize(file);
            return result;
        }

Done