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

C#开发 2014-05-19 26678阅读 0评论 0收藏 收藏本文

今天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; }
  }
}
由于是临时需求,所以简单得弄了一下,实现中用到了一些自己的类库,就不在这贴出来了。

转载请注明:图享网 » C#将Object序列化成XML并保存文件

文章评论

获取验证码