【XML操作】XMLTextWriter 创建、读取XML文档
时间:2011-05-19 来源:好大一棵草
1.XMLTextWriter创建XML文档
1 //创建XmlTextWriter类的实例对象
2 XmlTextWriter textWriter = new XmlTextWriter("D:\\introduce1.xml",null);
3 //设置格式,对元素内容进行缩进
4 textWriter.Formatting = Formatting.Indented;
5 //书写版本为“1.0”的XML声明
6 textWriter.WriteStartDocument();
7 //写出在名称和文本之间带有空格的处理指令
8 string PItext = "type = 'text/xsl' href = 'book.xsl' ";
9 textWriter.WriteProcessingInstruction("xml-stylesheet", PItext);
10 //增加指定名称和可选属性的DocType声明
11 textWriter.WriteDocType("学生",null,null,"<!ENTITY sex '男'>");
12 //增加注释
13 textWriter.WriteComment("XML注释");
14 //开始创建元素
15 textWriter.WriteStartElement("学生");
16 //创建属性
17 textWriter.WriteAttributeString("专业","计算机");
18 textWriter.WriteAttributeString("日期","2011-05-19");
19 //创建元素
20 textWriter.WriteElementString("姓名","好大一棵草");//创建元素1
21 textWriter.WriteStartElement("性别"); //创建元素2
22 textWriter.WriteEntityRef("sex"); //创建对上面实体的引用,显示时自动替换为:男
23 textWriter.WriteEndElement();
24 textWriter.WriteElementString("年龄","24");
25 //写CData信息
26 textWriter.WriteCData("年龄大了,该找女朋友了!");
27 //关闭根
28 textWriter.WriteEndElement();
29 textWriter.WriteEndDocument();
30 //最后写XML文件,并关闭textWriter
31 textWriter.Flush();
32 textWriter.Close();
33 Response.Write("写入成功");
2.XmlTextReader读取XML文档
1 //创建一个XmlTextReader类的对象并调用Read方法来读取文件
2 XmlTextReader textReader = new XmlTextReader("D:\\introduce1.xml");
3
4 //节点非空这执行循环体
5 textReader.Read();
6 while (textReader.Read())
7 {
8 }
9 //得到当前节点类型,执行相应处理
10 XmlNodeType nType = textReader.NodeType;
11 switch (nType )
12 {
13 case XmlNodeType.XmlDeclaration:
14 break;
15 case XmlNodeType.Comment:
16 break;
17 case XmlNodeType.Attribute:
18 break;
19 case XmlNodeType.Element:
20 break;
21 case XmlNodeType.DocumentType:
22 break;
23 case XmlNodeType.Whitespace:
24 break;
25 }
26 //读取该元素的各种属性值
27 textReader.MoveToElement();
28 Response.Write("Name:" +textReader.Name);
29 Response.Write("Base URI:" + textReader.BaseURI);
30 Response.Write("Local Name:" + textReader.LocalName);
31 Response.Write("Attributu Count:" + textReader.AttributeCount.ToString ());
32 Response.Write("Delth:" + textReader.Depth.ToString());
33 Response.Write("Line Number:" + textReader.LocalName .ToString());
34 Response.Write("Node Type:" + textReader.NodeType.ToString());
35 Response.Write("Attribute Count:" + textReader.Value.ToString());
相关阅读 更多 +