一.Xml的創建方式
-
- Xmlwriter(流式讀取,Stream)
寫過了:https://www.cnblogs.com/dengzhekaihua/p/15438493.html 這種方法雖然快,但是隻能寫一遍,一次性全部寫完,不方便進行修改
2.通過Xelement直接寫xml(Linq to xml)
- Xmlwriter(流式讀取,Stream)
點擊查看代碼
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();
點擊查看代碼
//使用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");