protected void btnCreate_Click(object sender, EventArgs e)
{
//定義XMLDocument
XmlDocument xmlDocument = new XmlDocument();
//定義XML文檔標頭檔
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
//增加XML文檔頭
xmlDocument.AppendChild(xmlDeclaration);
//定義XML的根
XmlElement xmlRoot = xmlDocument.CreateElement("Roots");
//添加XML的根
xmlDocument.AppendChild(xmlRoot);
//添加根的屬性
xmlRoot.SetAttribute("RootAttribute", "Value");
//修改根屬性的值
xmlRoot.GetAttributeNode("RootAttribute").Value = "FixValue";
//定義節點
XmlNode xmlElement;
//迴圈建立節點
for (int i = 0; i < 2; i++)
{
//建立XML根的節點
xmlElement = xmlDocument.CreateElement("Element");
//XML需要的屬性列表
foreach (KeyValuePair<String, String> keyValuePair in NameValueDictionary())
{
//定義XML根的節點中的屬性
XmlAttribute oneAttribute = xmlDocument.CreateAttribute(keyValuePair.Key);
oneAttribute.Value = keyValuePair.Value;
XmlAttribute secAttribute = xmlDocument.CreateAttribute(keyValuePair.Key);
secAttribute.Value = keyValuePair.Value;
//添加XML根的節點中的屬性
xmlElement.Attributes.Append(oneAttribute);
xmlElement.Attributes.Append(secAttribute);
//添加XML根的節點
xmlRoot.AppendChild(xmlElement);
}
}
//儲存XML文檔
xmlDocument.Save(Server.MapPath("OutDocument.XML"));
}
//XML需要的屬性列表
private Dictionary<String, String> NameValueDictionary()
{
Dictionary<String, String> nameValueDictionary = new Dictionary<String, String>();
nameValueDictionary.Add("AttributeOne", "One");
nameValueDictionary.Add("AttributeSec", "Second");
return nameValueDictionary;
}
產生的XML模組
<?xml version="1.0" encoding="utf-8"?>
<Roots RootAttribute="FixValue">
<Element AttributeOne="One" AttributeSec="Second" />
<Element AttributeOne="One" AttributeSec="Second" />
</Roots>