如何使用C#以编程方式生成/创建XML文件的最佳方法? [英] A best approach on how to generate/create a XML file programmatically using C#?

查看:163
本文介绍了如何使用C#以编程方式生成/创建XML文件的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨专家,



有人可以建议我使用除XmlReader / XmlWriter以外的C#以编程方式生成XML文件的最佳方法吗? (因此解析它应该更容易)。



基本上,它是NHibernate的Xml Hbm映射文件。任何可用于读取/写入Hbm文件的.NET Api,如Xaml,我们都有XamlReader / XamlWriter。



谢谢。

Hi Experts,

Can anybody suggest me a best approach on how to generate a XML file programmatically using C# other than XmlReader/XmlWriter? (so that parsing it should be easier).

Basically, it is a Xml Hbm mapping file for NHibernate. Any .NET Api available for reading/writing Hbm files like for Xaml we have XamlReader/XamlWriter.

Thanks.

推荐答案

您可以使用 XmlDocument [< a href =http://msdn.microsoft.com/en-us/library/vstudio/fw1ys7w6(v=vs.85).aspx\"target =_ blanktitle =New Window> ^ ]。

You can use XmlDocument[^].
XmlDocument xmlDoc = new XmlDocument();
XmlElement elRoot = xmlDoc.CreateElement("body");
xmlDoc.AppendChild(elRoot);

XmlElement elParam = xmlDoc.CreateElement("param");
XmlText elValue = xmlDoc.CreateTextNode("MyClass_SEQ");
elParam.AppendChild(elValue);
elParam.SetAttribute("name", "sequence");
elRoot.AppendChild(elParam);

XmlElement elProp = xmlDoc.CreateElement("property");
elProp.SetAttribute("name", "Prop1");
elProp.SetAttribute("column", "Column1");
elProp.SetAttribute("type", "Int32");
elRoot.AppendChild(elProp);

string s = xmlDoc.OuterXml;





如果你可以使用.NET3.5或更高版本,你也可以使用 XDocument [ ^ ]



If you can use .NET3.5 or later you can also use XDocument[^]

XDocument doc = new XDocument();
XElement xeBody = new XElement("body");     // Root element
XElement xeParam = new XElement("param", "MyClass_SEQ");
xeParam.Add(new XAttribute("name", "sequence"));
xeBody.Add(xeParam);

XElement xeProperty = new XElement("property");
xeProperty.Add(new XAttribute("name", "Prop1"));
xeProperty.Add(new XAttribute("column", "Column1"));
xeProperty.Add(new XAttribute("type", "Int32"));
xeBody.Add(xeProperty);

doc.Add(xeBody);
doc.Save(@"c:\Temp\test.xml");


System.Data.DataSet ds = new System.Data.DataSet();

System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(Select * from demo,Data Source = 184.107.55.15; Initial Catalog = demo; User ID = sa; Password = 1947);

da.Fill(ds);

//在这里写XML



ds.WriteXml(D:\\输出。 xml,System.Data.XmlWriteMode.WriteSchema);
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from demo", "Data Source=184.107.55.15;Initial Catalog=demo;User ID=sa;Password=1947");
da.Fill(ds);
// Write to XML here

ds.WriteXml("D:\\output.xml", System.Data.XmlWriteMode.WriteSchema);


这篇关于如何使用C#以编程方式生成/创建XML文件的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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