C#代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace CreateXML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
//创建XML的版本和编码
XmlDeclaration xd = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(xd);
//创建根节点
XmlElement orders = doc.CreateElement("Orders");
doc.AppendChild(orders);
//创建一级子节点
//创建第一个订单
XmlElement order1 = doc.CreateElement("Order");
orders.AppendChild(order1);
//创建二级子节点
XmlElement customerName = doc.CreateElement("CustomerName");
customerName.InnerText = "刘洋";
order1.AppendChild(customerName);
XmlElement customerNumber = doc.CreateElement("CustomerNumber");
customerNumber.InnerText = "BJ1000001";
order1.AppendChild(customerNumber);
XmlElement itemes = doc.CreateElement("Items");
order1.AppendChild(itemes);
//创建三级带属性的子节点
XmlElement orderItem1 = doc.CreateElement("OrderItem");
orderItem1.SetAttribute("Name", "码表");
orderItem1.SetAttribute("Count", "2");
itemes.AppendChild(orderItem1);
XmlElement orderItem2 = doc.CreateElement("OrderItem");
orderItem2.SetAttribute("Name", "雨衣");
orderItem2.SetAttribute("Count", "10");
itemes.AppendChild(orderItem2);
XmlElement orderItem3 = doc.CreateElement("OrderItem");
orderItem3.SetAttribute("Name", "手套");
orderItem3.SetAttribute("Count", "15");
itemes.AppendChild(orderItem3);
//创建第二个订单
XmlElement order2 = doc.CreateElement("Odeer");
orders.AppendChild(order2);
//创建第二个订单的一级子节点
XmlElement customerName2 = doc.CreateElement("CustomerName");
customerName2.InnerText = "李四";
order2.AppendChild(customerName2);
XmlElement customerNumber2 = doc.CreateElement("CustomerNumber");
customerNumber2.InnerText = "LS2142343";
order2.AppendChild(customerNumber2);
XmlElement items2 = doc.CreateElement("Items");
order2.AppendChild(items2);
XmlElement orderItem4 = doc.CreateElement("OrderItem");
orderItem4.SetAttribute("Name", "水浒传");
orderItem4.SetAttribute("Count", "1");
items2.AppendChild(orderItem4);
XmlElement orderItem5 = doc.CreateElement("OrderItem");
orderItem5.SetAttribute("Name", "红楼梦");
orderItem5.SetAttribute("Count", "5");
items2.AppendChild(orderItem5);
doc.Save("Odrer.xml");
MessageBox.Show("XML文档创建成功!");
}
}
}