首页 / C#开发 / 正文

C#将Object序列化成XML并保存文件

30790 发布于: 2014-05-19 读完约需10分钟
今天BOSS有个临时需求,即调用部分数据生成网站对应的GOOGLE XML地图文件,此需求的要点是将类对象(Urlset)序列化成XML文档,话不多说,直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace WinformTest
{
  public partial class frmLrXmlSiteMap : Form
  {
    private int _start = 0;
    private int _limit = 100;
    private int _max = 134985;
    private Urlset _list = new Urlset();

    public frmLrXmlSiteMap()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

      //TODO:加载数据
      Task.Factory.StartNew(() =>
      {
        while (_start < _max)
        {
          try
          {
            LoadData();
            MySerializeXml(_list);
            UpdateLogControl(string.Format("XML已生成,Start:{0}.", _start));
            Thread.Sleep(2000);
          }
          catch (Exception ex)
          {
            UpdateLogControl(string.Format("出错啦:{0}", ex.ToString()));
          }
        }
      });
    }

    protected void LoadData()
    {
      _list.urls.Clear();
      UpdateLogControl("正在加载TOPIC...");
      var sql = string.Format("SELECT topic_alias FROM 表名 WHERE article_total>=3 ORDER BY topic_id LIMIT {0},{1}", _start, _limit);
      var ds = MySqlHelper_Lr.Query(sql);
      if (ds != null && ds.Tables[0].Rows.Count > 0)
      {
        _start += _limit;
        DataTable dt = ds.Tables[0];
        ds.Dispose();

        _list.urls = (from x in dt.AsEnumerable()
                      select (new Url
                      {
                        changefreq = "weekly",
                        loc = string.Format("http://xxxxx.com/topic/{0}", x.Field<string>("topic_alias")),
                        priority = 0.9
                      })).ToList();
      }
    }

    public void MySerializeXml(Urlset obj)
    {
      System.Xml.Serialization.XmlSerializer writer =
            new System.Xml.Serialization.XmlSerializer(typeof(Urlset));
      StreamWriter file = new System.IO.StreamWriter(
            @"c:lr" + StringUtility.getRandomizer(10, true, false, true, true) + ".xml");
      writer.Serialize(file, obj);
      file.Close();
    }

    protected void UpdateLogControl(string msg)
    {
      if (rtxtLog.InvokeRequired)
      {
        rtxtLog.Invoke(new Action(() =>
        {
          rtxtLog.AppendText(string.Format("{0}==>>{1}{2}", DateTime.Now, msg, Environment.NewLine));
        }));
      }
      else
      {
        rtxtLog.AppendText(string.Format("{0}==>>{1}{2}", DateTime.Now, msg, Environment.NewLine));
      }
    }
  }

  [Serializable]
  public class Url
  {
    [DefaultValue("")]
    [XmlElement("loc")]
    public string loc { get; set; }
    [XmlElement("changefreq")]
    public string changefreq { get; set; }
    [XmlElement("priority")]
    public double priority { get; set; }
  }
  [Serializable]
  [XmlElement("urlset")]
  public class Urlset
  {
    public Urlset()
    {
      urls = new List<Url>();
    }
    [XmlElement("url")]
    public List<Url> urls { get; set; }
  }
}
由于是临时需求,所以简单得弄了一下,实现中用到了一些自己的类库,就不在这贴出来了。

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: Visual Studio 2013错误--No exports were found that match the constraint contract name

下一篇: Ubuntu 14.04中Firefox安装Flash插件

本文永久链接码友网 » C#将Object序列化成XML并保存文件

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册