写代码的时候经常想把一个 实体类对象转成xml文本查看,
比如说我想把下面的student对象转为xml
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Niaj { get; set; }
}
转为
<Student>
<Name>Tom</Name>
<Age>9</Age>
<Niaj>1nianji</Niaj>
</Student>
我写了一个简单的convert类,本人菜鸟,写错了的话请见谅。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//新加namespace
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace MyObjToXML
{
public class ConvertToXML
{
public void ObjToXML(object obj)
{
try
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
//日志文件夹路径
string LogFileWJJ = AppDomain.CurrentDomain.BaseDirectory + "MyLog";
if (File.Exists(LogFileWJJ) == false)
{
//不存在MyLog文件夹就创建
Directory.CreateDirectory(LogFileWJJ);
}
string fileName = string.Format("{0}\\Myxml{1}.xml", LogFileWJJ , DateTime.Now.ToString("yyyyMMddhhmmss"));
TextWriter tw = new StreamWriter(fileName);
xs.Serialize(tw, obj);
tw.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}//end class
}