生成XML文件,并保存到本地文件
生成如下结构的XML文件:
<anychart> <charts> <chart plot_type="CategorizedVertical"> <data> <series name="Year 2003" type="Bar"> <point name="AAA" y="7649" /> <point name="BBB" y="4567" /> <point name="CCC" y="6410" /> </series> </data> <chart_settings> <title> <text>销售<text> </title> <axes> <y_axis> <title>Sales</title> </y_axis> <x_axis> <title>Retail Channel</title> </x_axis> </axes> </chart_settings> </chart> </charts> </anychart>
代码如下:
protected void Page_Load(object sender, EventArgs e) { DataBind databind = new DataBind(); DataSet ds = databind.ABCData(); string plot_type = "CategorizedVertical"; XmlDocument doc = new XmlDocument(); XmlElement Node = doc.CreateElement("anychart");//创建一个anychart节点 doc.AppendChild(Node); XmlElement Node1 = doc.CreateElement("charts");//创建节点anychart子节点charts doc.DocumentElement.AppendChild(Node1); XmlElement Node2 = doc.CreateElement("chart");//创建节点charts子节点chart Node2.SetAttribute("plot_type", plot_type);//为节点chart添加plot_type属性 Node1.AppendChild(Node2); XmlElement Node3 = doc.CreateElement("data");//创建节点chart第一个子节点data Node2.AppendChild(Node3); XmlElement Node4 = doc.CreateElement("chart_settings");//创建节点chart第二个子节点chart_settings Node2.AppendChild(Node4); XmlElement Node5 = doc.CreateElement("series");//创建节点data子节点series Node5.SetAttribute("name", "Year 2003");//为series节点添加第一个属性name Node5.SetAttribute("type", "Bar");//为series节点添加第二个属性type Node3.AppendChild(Node5); for (int i = 1; i <= 3; i++) { XmlElement Node13 = doc.CreateElement("point");//在节点series中创建子节点point Node13.SetAttribute("name", ds.Tables[0].Rows[i - 1]["products_Name"].ToString());//为point节点添加属性name并将ds.Tables[0]中products_Name一列数据逐行取出,赋值给属性name Node13.SetAttribute("y", ds.Tables[0].Rows[i - 1]["products_Quantity"].ToString());//为point节点添加属性y并将ds.Tables[0]中products_Quantity一列数据逐行取出,赋值给属性y Node5.AppendChild(Node13); } XmlElement Node6 = doc.CreateElement("title"); Node4.AppendChild(Node6); XmlElement Node7 = doc.CreateElement("axes"); Node4.AppendChild(Node7); XmlElement Node8 = doc.CreateElement("y_axis"); Node7.AppendChild(Node8); XmlElement Node9 = doc.CreateElement("x_axis"); Node7.AppendChild(Node9); XmlElement Node10 = doc.CreateElement("title"); Node10.InnerText = "Sales";//为节点title赋值Sales Node8.AppendChild(Node10); XmlElement Node11 = doc.CreateElement("title"); Node11.InnerText = "Retail Channel"; Node9.AppendChild(Node11); XmlElement Node12 = doc.CreateElement("text"); Node12.InnerText = "销售"; Node6.AppendChild(Node12); doc.Save("D:\test.xml"); //保存xml }
如果想判断一下文件D:\test.xml是否存在,可以通过如下的代码进行:
string path = "D:\test.xml"; if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); }
最后把path传给doc.save(path)就OK了……
更多前端内容请访问个人博客:殷路辉的个人博客