C# 操作xml与对象转化用什么方法?
<?xml version= "1.0 " encoding= "UTF-8 "?>
<users>
<user id= "Rich " name= "Rich " password= "1 " address= "33/2 Mary ST Strathfield NSW 2250 "/>
<user id= "Randy " name= "Randy " password= "1 " address= "37/7 Jones ST Summer Hill NSW 2258 "/>
<user id= "Shelly " name= "Shelly " password= "1 " address= "3/2 Kingscross ST city NSW 2250 "/>
<user id= "Vincent " name= "Vincent " password= "1 " address= "36/7 George ST Chippendale NSW 2250 "/>
<user id= "Jay " name= "Jay " password= "1 " address= "33/2 Pancake ST Epping NSW 2250 "/>
<user id= "Andy " name= "Andy " password= "1 " address= "33/2 Jhon ST Telopia NSW 2250 "/>
</users>
以上是一个简单的xml文件 定义了一个User的列表
我现在想用一个User类 通过代码把这个xml中的每个 <user> 结点取出来,放到User类里面
也就是说xml与对象的转化 同理,我也需要反过来将User对象的集合转化到一个xml文件中,
请问有没有直接的方法呢?
一个个属性读取xml 然后拼凑User对象的方法就免了,因为这种笨办法谁都能想到
------解决方案--------------------XML学习(Working with XML):
1.幻灯片课程
下载: http://www.cnblogs.com/Files/ChengKing/Working%20with%20XML(ppt).rar
2.示例代码
下载: http://www.cnblogs.com/Files/ChengKing/Working%20with%20XML(project).rar
http://blog.csdn.net/ChengKing/archive/2006/03/31/646363.aspx
------解决方案--------------------.net 提供 xml 的序列化以及反序列化
你可以直接使用 System.Xml.Serialization.XmlSerializer 完成此项功能
DEMO 在:
http://msdn2.microsoft.com/zh-cn/library/system.xml.serialization.xmlserializer(VS.80).aspx
------解决方案--------------------using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;
[Serializable]
public class user
{
string _id;
[XmlAttribute(AttributeName= "id ")]
public string id
{
get { return _id; }
set { _id = value; }
}
string _name;
[XmlAttribute(AttributeName = "name ")]
public string name
{
get { return _name; }
set { _name = value; }
}
string _password;
[XmlAttribute(AttributeName = "password ")]
public string password
{
get { return _password; }
set { _password = value; }
}
string _address;
[XmlAttribute(AttributeName = "address ")]
public string address
{
get { return _address; }
set { _address = value; }
}
}
public class UserSerialize
{
public static string SerializeUsers(user[] Users)
{
StringBuilder sb=new StringBuilder();
StringWriter w=new StringWriter(sb);