C#怎么把数据库转换成固定格式的XML文件
答案:2 悬赏:40 手机版
解决时间 2021-02-12 10:31
- 提问者网友:杀手的诗
- 2021-02-12 03:25
C#怎么把数据库转换成固定格式的XML文件
最佳答案
- 五星知识达人网友:平生事
- 2021-02-12 03:36
1、将数据库的内容读取到dataTable或dataSet中
2、dataTable或dataSet转为xml
private string ConvertDataTableToXML(DataTable xmlDS) //DataTable可改用dataset
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.Default);
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim();
}
catch
{
return String.Empty;
}
finally
{
if (writer != null) writer.Close();
}
}
2、dataTable或dataSet转为xml
private string ConvertDataTableToXML(DataTable xmlDS) //DataTable可改用dataset
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.Default);
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim();
}
catch
{
return String.Empty;
}
finally
{
if (writer != null) writer.Close();
}
}
全部回答
- 1楼网友:野慌
- 2021-02-12 03:47
很高兴可以给你解答! xml实际就是一个本地简单的数据库 我只做了一个简单的。。但是道理是一样的。 //xml文件信息 <abc> <field>100</field> <item> <id>1</id> <name>zhangsan</name> <sex>男</sex> </item> <item> <id>2</id> <name>lisi</name> <sex>男</sex> </item> </abc> //实体类。 public class information { private string id; public string id { get { return id; } set { id = value; } } private string name; public string name { get { return name; } set { name = value; } } private string sex; public string sex { get { return sex; } set { sex = value; } } public information() { } public information(string id,string name,string sex) { this.id = id; this.name = name; this.sex = sex; } } //读取xml里面的文件信息 list<information> list = new list<information>(); //实例化xml xmldocument xml = new xmldocument(); //读取xml文件 xml.load(@"e:\c#\s2c#\dlcl\打印电脑\mycomputer\xuliehua\xml.xml"); //你的xml地址 string id = ""; string name = ""; string sex = ""; information info = null; ///////// /////////////// foreach (xmlnode node in xml.childnodes) { if (node.name == "abc") { foreach (xmlnode node1 in node.childnodes) { if (node1.name == "item") { foreach (xmlnode node2 in node1.childnodes) { switch (node2.name) { case "id": id = node2.innertext; break; case "name": name = node2.innertext; break; default: sex = node2.innertext; break; } } info = new information(id, name, sex); //将信息保存至集合 list.add(info); } } } } xml里面的所有信息就是在list集合里面了。。简单吧。。嘿嘿。。 当然你可以做多个表和多个字段属性咯。。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯