C#Xml的三種創建方式(或者是兩種?)和增刪改查

一.Xml的創建方式

點擊查看代碼
	XElement xElement = new XElement(
			  new XElement("ProductType",
				  new XElement("BMW",
					  new XElement("Threshold", "Search", new XAttribute("Max", 100)),//後面這個是obj類型,寫啥都行,輸出的時候XAttribute.Value都是string類型
					  new XElement("Threshold", "Search", new XAttribute("Min", "20")),
					  new XElement("ROI", "Rect1"),
					  new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
					  ),
				   new XElement("Volvo",
					new XElement("Threshold", "Search", new XAttribute("Max", 100)),
					  new XElement("Threshold", "Search", new XAttribute("Min", "20")),
					  new XElement("ROI", "Rect2"),
					  new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
					   )));
			string iniPath = Application.StartupPath + "\\params";
			string xmlPath = iniPath + "\\ProductInfo.xml";
			//需要指定編碼格式,否則在讀取時會拋:根級別上的數據無效。 第 1 行 位置 1異常
			XmlWriterSettings settings = new XmlWriterSettings();
		        settings.Encoding = new UTF8Encoding(false);
		        settings.Indent = true;
		        XmlWriter xw = XmlWriter.Create(xmlPath, settings);//不用xmlwriter 用document寫也一樣的,但是writer快一點
		        xElement.Save(xw);
                        xw.Flush();
		        xw.Close();
3. 使用Xdocument建立(樹結構,速度比writer慢,不推薦)
點擊查看代碼
 
          //使用XDocument創建xml
             System.Xml.Linq.XDocument xdoc = new XDocument();
             XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
             xdoc.Declaration = xdec;
  
              //添加根節點
             XElement rootEle = new XElement("school");
             xdoc.Add(rootEle);
 
             //給根節點添加子節點
             XElement classEle = new XElement("class");
             XAttribute attrClass = new XAttribute("No", 1);
             classEle.Add(attrClass);
             rootEle.Add(classEle);//其實就是看哪個Xelement.Add的,哪個加的哪個就是誰的子節點

             XElement classEle1 = new XElement("class1");
             XAttribute attrClass1 = new XAttribute("No", 1);
             classEle1.Add(attrClass1);
             rootEle.Add(classEle1);

             //添加子節點下的元素
             XElement stuEle = new XElement("student");
             XAttribute atrStu = new XAttribute("sid", "20180101");
             stuEle.Add(atrStu);
             classEle.Add(stuEle);

             //保存文件
             xdoc.Save("d:\\zzz\\TestB.xml");

二.Xml的增加 1.可以用上面第三種裏面的XElement.Add()去添加節點到對應的位置 //沒寫完
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章