1. 實現代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace _03創建帶屬性的XML
{
class Program
{
static void Main(string[] args)
{
//第一步
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
//第二步
XmlElement order = doc.CreateElement("Order");
doc.AppendChild(order);
//第三步
XmlElement customername = doc.CreateElement("CustomerName");
customername.InnerText="劉洋";
order.AppendChild(customername);
//第四步
XmlElement ordernumber = doc.CreateElement("OrderNumber");
ordernumber.InnerText = "010100";
order.AppendChild(ordernumber);
//第五步
XmlElement items = doc.CreateElement("Items");
order.AppendChild(items);
//第六步
XmlElement items1 = doc.CreateElement("OrderItem");
items1.SetAttribute("Name", "手錶");
items1.SetAttribute("Count", "10");
items.AppendChild(items1);
//第七步
XmlElement items2 = doc.CreateElement("OrderItem");
items2.SetAttribute("Name", "手機");
items2.SetAttribute("Count", "100");
items.AppendChild(items2);
doc.Save("Atrribute.xml");
Console.WriteLine("保存完畢");
Console.ReadKey();
}
}
}
2. 運行結果: