使用xml串行化将对象保存为xml数据

本文介绍如何使用C#中的XmlSerializer将Person对象数组序列化为XML文件。通过实例展示了如何设置XmlRoot属性来定义根元素名称及命名空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace IOStream
{

public class Person
{
public Person() { }

private int id;
private string name;
private string place;
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Place
{
get { return place; }
set { place = value; }
}

}

/*使用xml串行化将对象保存为xml数据*/
class StringTest
{
public static void Main()
{
Person p1 = new Person();
p1.Id = 1;
p1.Name = "小明";
p1.Place = "武汉";

Person p2 = new Person();
p2.Id = 2;
p2.Name = "许愿";
p2.Place = "南昌";
Person p3 = new Person();
p3.Id = 3;
p3.Name = "有娴心";
p3.Place = "成都";

Person[] ps ={ p1, p2, p3 };

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "people";
xRoot.Namespace = "http://www.xx.com";
xRoot.IsNullable = true;
XmlSerializer xSerial = new XmlSerializer(typeof(Person[]), xRoot);
string filename = @"c:\people.xml";
TextWriter writer = new StreamWriter(filename);
xSerial.Serialize(writer, ps);

Console.ReadLine();
}
}


}



运行结果如下:


<?xml version="1.0" encoding="utf-8"?>
<people xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xx.com">
<Person>
<Id>1</Id>
<Name>小明</Name>
<Place>武汉</Place>
</Person>
<Person>
<Id>2</Id>
<Name>许愿</Name>
<Place>南昌</Place>
</Person>
<Person>
<Id>3</Id>
<Name>有娴心</Name>
<Place>成都</Place>
</Person>
</people>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值