一.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");
XDocument 属性
三.Xml的增加
1.可以用上面第三种里面的XElement.Add()去添加节点到对应的位置
//没写完