基于流的XML处理,用到两个类XmlTextWriter和XmlTextReader。
写入方法:
声明XmlTextWriter
string xmlFilePath = Path.Combine(Environment.CurrentDirectory, @"DvdList.xml"); XmlTextWriter writer = new XmlTextWriter(xmlFilePath, null);
声明Formatting
writer.Formatting = Formatting.Indented; writer.Indentation = 3;
声明版本
writer.WriteStartDocument();
写入注释
writer.WriteComment("Create By Ray Xu @" + DateTime.Now.ToString());
写入开始节点和结束节点
writer.WriteStartElement("DvdList"); writer.WriteEndElement();
写入特性和元素
writer.WriteAttributeString("ID", "1"); writer.WriteElementString("Title", "The Matrix");
读取方法:
调用reader.Read()方法,判断reader.NodeType,可以获取reader.Name和reader.Value。
读取节点后,检查是否具有属性。reader.AttributeCount>0。循环调用reader.MoveToNextAttribute()。