XML:Extensible Markup Language(可擴展標記語言)
優點:容易讀懂;格式標准任何語言都內置了XML分析引擎,不用單獨進行文件分析引擎的編寫;可以使用記事本打開,足夠方便
XML語法規范:標簽、嵌套、屬性。標簽要閉合,屬性值要用“”包圍,標簽可以相互嵌套
- XML和HTML的區別:
- 有且只能有一個根元素
- XML中元素必須關閉
- XML中元素的屬性必須使用引號
- XML大小寫敏感
程序操作XML的三種方式:
- XmlDocument方式操作XML,net2.0可以使用
- XDocument方式操作XML,net3.x以上可以使用
- SAX方式操作XML(收費,不用)
- XML序列化:XmlSerializer
本文介紹使用XmlDocument創建Dom對象並寫入XML中
1.在內存中創建一個Dom對象
XmlDocument xmlDoc = new XmlDocument();
1.2.增加一個文檔說明
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
1.3.將文檔說明加入到Dom對象中
xmlDoc.AppendChild(xmlDeclaration);
2.1.創建一個根節點(每個Dom對象必須有根節點)
XmlElement rootElement = xmlDoc.CreateElement("school");
2.2將根節點追加到Dom對象中
xmlDoc.AppendChild(rootElement);
3.1為根節點增加子節點
XmlElement xmlClassElement=xmlDoc.CreateElement("class");
3.2.給子節點增加一個名字為id的屬性
XmlAttribute attr = xmlDoc.CreateAttribute("id"); attr.Value = "c01"; xmlClassElement.Attributes.Append(attr);
3.3將class節點添加到根節點下
rootElement.AppendChild(xmlClassElement);
4.將該Dom對象寫入xml文件中
xmlDoc.Save("school.xml");
例子:將集合中的信息寫入到xml中
List<Person> list = new List<Person>(); list.Add(new Person() { Id=1,Name="張三",Age=12}); list.Add(new Person() { Id = 6, Name = "張5", Age = 13 }); list.Add(new Person() { Id = 2, Name = "張4", Age = 14 }); list.Add(new Person() { Id = 3, Name = "張3", Age = 15 }); list.Add(new Person() { Id = 4, Name = "張2", Age = 16 }); list.Add(new Person() { Id = 5, Name = "張1", Age = 17 }); XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); xmlDoc.AppendChild(xmlDec); XmlElement xmlRoot = xmlDoc.CreateElement("school"); xmlDoc.AppendChild(xmlRoot); for (int i = 0; i < list.Count; i++) { XmlElement xmlPerson = xmlDoc.CreateElement("person"); XmlAttribute attrId=xmlDoc.CreateAttribute("id"); attrId.Value = list[i].Id.ToString(); xmlPerson.Attributes.Append(attrId); XmlElement xmlName=xmlDoc.CreateElement("name"); xmlName.InnerText = list[i].Name; xmlPerson.AppendChild(xmlName); XmlElement xmlAge = xmlDoc.CreateElement("age"); xmlAge.InnerText = list[i].Age.ToString(); xmlPerson.AppendChild(xmlAge); xmlRoot.AppendChild(xmlPerson); } xmlDoc.Save("Student.xml");