在C#中读取此xml的最佳方法

时间:2018-08-09 14:33:39

标签: c# asp.net xml model-view-controller

这是我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<users>
  <user id="12">
    <Nome>pedro</Nome>
    <Email>pedro.roldan@gmail.com</Email>
    <DataNascimento>1976-01-01</DataNascimento>
    <Foto>E:\Trabalho\web\12_7a639ffac9146d346372eb7598e1642f.jpg</Foto>
  </user>
  <user id="13">
    <Nome>DORA</Nome>
    <Email>dora.bilro@gmail.com</Email>
    <DataNascimento>2003-02-12</DataNascimento>
    <Foto>E:\Trabalho\web\13_135bb70e258379ee643d575bd688a692.jpg</Foto>
  </user>
  <user id="14">
    <Nome>dcdc</Nome>
    <Email>rui.moura@ff.pt</Email>
    <DataNascimento>1998-03-25</DataNascimento>
    <Foto>E:\Trabalho\web\14_7a639ffac9146d346372eb7598e1642f.jpg</Foto>
  </user>
</users>

我正在尝试将其导入asp.net mvc。

将其读入C#列表的最佳方法是什么? 预先感谢!

1 个答案:

答案 0 :(得分:1)

XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));

using(FileStream stream = File.OpenWrite("filename"))
{
  List<MyClass> list = new List<MyClass>();
  serializer.Serialize(stream, list);
}

using(FileStream stream = File.OpenRead("filename"))
{
  List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);
}

来自How to read a XML file and write into List<>?