XML序列化示例

首先把给project里面加个app.config,然后write into “ <add key="XmlFileString" value="/MyXMLFile.xml"/>”,主要是用ConfigurationSettings.AppSettings["XmlFileString"]来方便读取

贴个demo出来
<?xml version="1.0" encoding="utf-8" ?>
<XmlInfo>  <!--xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"-->
  <objDesisionTendencyColumnInfo>
    <clsGridDef>
      <stTitle>案件名称</stTitle>
      <strField>AJ.AJMC</strField>
    </clsGridDef>
    <clsGridDef>
      <stTitle>部门受案号</stTitle>
      <strField>AJ.BMSAH</strField>
    </clsGridDef>
    <clsGridDef>
      <stTitle>案件来源</stTitle>
      <strField>AJ.AJLY_MC</strField>
    </clsGridDef>
    <clsGridDef>
      <stTitle>受理时间</stTitle>
      <strField>AJ.SLRQ</strField>
    </clsGridDef>
  </objDesisionTendencyColumnInfo>
</XmlInfo>


create a class:
 [Serializable]
    public class clsGridDef
    {
        public clsGridDef()
        { }
        public string stTitle;    //标题
        public string strField;   //对应字段名称
    }

clsGridDef是类名称,对应xml里面的clsGridDef,成员stTitle和strField名称也不能写错。

then create a class:
 [Serializable]
    public class XmlInfo
    {
        public XmlInfo()
        {         
        }
        public clsGridDef[] objDesisionTendencyColumnInfo;
    }
一样,objDesisionTendencyColumnInfo是对应的xml中的objDesisionTendencyColumnInfo,不能写错,否则提示你文档内有错!

其实最后这个xmlInfo是可以不要的,但是我们的xml文件里面不可能只放一个class来用吧,这里的xmlInfo有点类似于名称空间。是所有序列化类的集合。方便管理和使用!

再来看看怎么调用它:
static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
XmlInfo xmlInfo = null;
            FileStream objFile = null;
            try
            {
                XmlSerializer Ser = new XmlSerializer(typeof(XmlInfo));
                objFile = new FileStream(
               Application.StartupPath+  ConfigurationSettings.AppSettings["XmlFileString"].ToString(), FileMode.Open);//
                StreamReader objRead = new StreamReader(objFile, Encoding.Default);
                xmlInfo = (XmlInfo)Ser.Deserialize(objRead);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message );
            }
            finally
            {
                if (objFile != null)
                {
                    objFile.Close();
                    objFile.Dispose();
                }
            } 
    }
}
ok,已经搞定!底层实现偶不是很清楚,这只是简单的用下而已,写在这里方便以后使用!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值