将数据从数据库传输到XML? [英] transfer data from database to XML?

查看:105
本文介绍了将数据从数据库传输到XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的开发人员,
如何将数据从数据库传输到xml文件(使用xml序列化).我需要将国家,州,城市和地址表转移到单个xml文件中.所有都是单独的表.

Dear Developers,
How to transfer data from database to xml file(using xml serialization). I need to transfer the country, state, city and address tables to a single xml file. All are separate tables.

<tblcountry>
<countryid>1</countryid>
<countryname>India</countryname>
</tblcountry>
<tblstate>
<stateid>1</stateid>
<statename>Tamilnadu</statename>
</tblstate>


等等.....


etc.....

推荐答案

假设您有如下所示的类:
Assume you have the classes like below :
[Serializable]
public class XmlInformation
{
  private List<Country> myCountry = new List<Country>();
  private List<State> myState = new List<State>();
  public List<Country> Country
  {
    get{ return myCountry; }
    set { myCountry = value; }
  }
  public List<State> State 
  {
    get{ return myState; }
    set { myState = value; }
  }
}
[Serializable]
public class Country
{
  private int myCountryId;
  private string myCountryName;
  public int CountryID
  {
    get{ return myCountryId; }
    set { myCountryId = value; }
  }
  public string CountryName
  {
    get{ return myCountryName; }
    set { myCountryName = value; }
  }
}
[Serializable]
public class State
{
  private int myStateId;
  private string myStateName;
  public int StateID
  {
    get{ return myStateId; }
    set { myStateId = value; }
  }
  public string StateName
  {
    get{ return myStateName; }
    set { myStateName = value; }
  }
}



使用序列化,您将能够像问题中的XML片段一样导出类:



You''ll be able to export the classes just like the XML fragment in your question using serialization :

XmlInformation xmlClassToExport = new XmlInformation();
using (StreamWriter swExport = new StreamWriter("path\to\filename"))
{
  XmlSerializer obj = new XmlSerializer(typeof(XmlInformation));
  obj.Serialize(swExport, xmlClassToExport);
  SW.Close();
}


一种方法是将所需数据读入DataTable并使用它的WriteXml [
One way would be to read the required data into a DataTable and use it''s WriteXml[^] method to produce the xml file. Not strictly xml serialization but far simpler IMO.




您可以使用System.Xml.Serialization命名空间.

在这里,我提供了示例代码
Hi,

You can use System.Xml.Serialization namespace.

Here I am providing a sample code
A a = new A();
XmlSerializer obj = new XmlSerializer(a.GetType());
StreamWriter SW = new StreamWriter("C:\\a.xml");
obj.Serialize(SW, a);
SW.Close();



其中A是包含数据的类.

问候
Ankit



Where A is a class which contains data.

Regards
Ankit


这篇关于将数据从数据库传输到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆