C#怎么把XML转成对象
时间: 2024-10-21 15:02:40 浏览: 15
在C#中,可以使用`System.Xml.Serialization`命名空间下的`XmlSerializer`类将XML转换为对象。以下是基本步骤:
1. 定义XML文件结构的模型类(例如,如果你有一个包含员工信息的XML文档,你需要创建一个Employee类):
```csharp
[Serializable]
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
// 添加更多属性...
}
```
2. 创建一个方法来序列化XML到对象:
```csharp
using System.IO;
using System.Xml.Serialization;
public static Employee ConvertXmlToEmployee(string xml)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var serializer = new XmlSerializer(typeof(Employee));
return (Employee)serializer.Deserialize(stream);
}
}
```
3. 调用这个方法并传入XML字符串:
```csharp
string xmlString = "<Employee><Name>John Doe</Name><Age>30</Age></Employee>";
Employee employee = ConvertXmlToEmployee(xmlString);
```
阅读全文