欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现XML与实体类之间相互转换的方法(序列化与反序列化)

程序员文章站 2022-05-28 19:27:05
本文实例讲述了c#实现xml与实体类之间相互转换的方法。分享给大家供大家参考,具体如下: using system; using system.collecti...

本文实例讲述了c#实现xml与实体类之间相互转换的方法。分享给大家供大家参考,具体如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.io;
using system.data;
using system.xml;
using system.xml.serialization;
/// <summary>
/// xml序列化与反序列化
/// </summary>
public class xmlutil
{
  #region 反序列化
  /// <summary>
  /// 反序列化
  /// </summary>
  /// <param name="type">类型</param>
  /// <param name="xml">xml字符串</param>
  /// <returns></returns>
  public static object deserialize(type type, string xml)
  {
    try
    {
      using (stringreader sr = new stringreader(xml))
      {
        xmlserializer xmldes = new xmlserializer(type);
        return xmldes.deserialize(sr);
      }
    }
    catch (exception e)
    {
      return null;
    }
  }
  /// <summary>
  /// 反序列化
  /// </summary>
  /// <param name="type"></param>
  /// <param name="xml"></param>
  /// <returns></returns>
  public static object deserialize(type type, stream stream)
  {
    xmlserializer xmldes = new xmlserializer(type);
    return xmldes.deserialize(stream);
  }
  #endregion
  #region 序列化
  /// <summary>
  /// 序列化
  /// </summary>
  /// <param name="type">类型</param>
  /// <param name="obj">对象</param>
  /// <returns></returns>
  public static string serializer(type type, object obj)
  {
    memorystream stream = new memorystream();
    xmlserializer xml = new xmlserializer(type);
    try
    {
      //序列化对象
      xml.serialize(stream, obj);
    }
    catch (invalidoperationexception)
    {
      throw;
    }
    stream.position = 0;
    streamreader sr = new streamreader(stream);
    string str = sr.readtoend();
    sr.dispose();
    stream.dispose();
    return str;
  }
  #endregion
}

/* 实体对象转换到xml */
public class student
{
  public string name { set; get; }
  public int age { set; get; }
}
student stu1 = new student() { name = "okbase", age = 10 };
string xml = xmlutil.serializer(typeof(student), stu1);
console.write(xml);
/* xml转换到实体对象 */
student stu2 = xmlutil.deserialize(typeof(student), xml) as student;
console.write(string.format("名字:{0},年龄:{1}", stu2.name, stu2.age));
/* datatable转换到xml */
// 生成datatable对象用于测试
datatable dt1 = new datatable("mytable");  // 必须指明datatable名称
dt1.columns.add("dosage", typeof(int));
dt1.columns.add("drug", typeof(string));
dt1.columns.add("patient", typeof(string));
dt1.columns.add("date", typeof(datetime));
// 添加行
dt1.rows.add(25, "indocin", "david", datetime.now);
dt1.rows.add(50, "enebrel", "sam", datetime.now);
dt1.rows.add(10, "hydralazine", "christoff", datetime.now);
dt1.rows.add(21, "combivent", "janet", datetime.now);
dt1.rows.add(100, "dilantin", "melanie", datetime.now);
// 序列化
xml = xmlutil.serializer(typeof(datatable), dt1);
console.write(xml);
/* xml转换到datatable */
// 反序列化
datatable dt2 = xmlutil.deserialize(typeof(datatable), xml) as datatable;
// 输出测试结果
foreach (datarow dr in dt2.rows)
{
  foreach (datacolumn col in dt2.columns)
  {
    console.write(dr[col].tostring() + " ");
  }
  console.write("\r\n");
}
/* list转换到xml */
// 生成list对象用于测试
list<student> list1 = new list<student>(3);
list1.add(new student() { name = "okbase", age = 10 });
list1.add(new student() { name = "csdn", age = 15 });
// 序列化
xml = xmlutil.serializer(typeof(list<student>), list1);
console.write(xml);
/* xml转换到list */
list<student> list2 = xmlutil.deserialize(typeof(list<student>), xml) as list<student>;
foreach (student stu in list2)
{
  console.writeline(stu.name + "," + stu.age.tostring());
}

protected void page_load(object sender, eventargs e)
{
  string strtest = @"<relationships>
   <variationparent xmlns='http://www.microsoft.com/schema/products/2011-10-01'>
    <identifiers>
     <marketplaceasin>
      <marketplaceid>atvpdkikx0der</marketplaceid>
      <asin>b00k69wurq</asin>
     </marketplaceasin>
     <marketplaceasin>
      <marketplaceid>tbvpdkikx0der</marketplaceid>
      <asin>c00k69wurq</asin>
     </marketplaceasin>
     <marketplaceasin>
      <marketplaceid>klvpdkikx0der</marketplaceid>
      <asin>d00k69wurq</asin>
     </marketplaceasin>
    </identifiers>
   </variationparent>
  </relationships>";
  textbox1.text = "";
  xmldocument doc = new xmldocument();
  doc.loadxml(strtest);
  xmlelement root = doc.documentelement;
  //用于带命名空间的xml操作
  xmlnamespacemanager nsmgr = new xmlnamespacemanager(doc.nametable);
  nsmgr.addnamespace("ab", "http://www.microsoft.com/schema/products/2011-10-01");
  xmlnodelist macthnodes = root.selectnodes("//ab:identifiers/ab:marketplaceasin", nsmgr);
  for (int i = 0; i < macthnodes.count; i++)
  {
    //删除生成的命名空间,生成标准xml。
    string matchnode = cleanxmlnstag(macthnodes[i].outerxml);
    marketplaceasin ma = xmlutil.deserialize(typeof(marketplaceasin), matchnode) as marketplaceasin;
    if (ma != null)
    {
      response.write(ma.marketplaceid + "---------" + ma.asin + "<br/>");
    }
  }
}
/* 实体对象 */
public class marketplaceasin
{
  public string marketplaceid { set; get; }
  public string asin { set; get; }
}
protected string cleanxmlnstag(string xml)
{
  xml = xml.replace("xmlns=\"http://www.microsoft.com/schema/products/2011-10-01\"", "");
  return xml;
}

ps:小编这里再来为大家推荐几款关于xml操作的在线工具供大家免费使用。相信在以后开发中可以用的到:

在线xml格式化/压缩工具:

在线xml/json互相转换工具:

xml代码在线格式化美化工具:

html/xml转义字符对照表:

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。