XmlTextReader是类似于SAX的基于流的Xml读取器,与SAX不同的是,SAX采取的是push model推模式,XmlTextReader采用的是pull model,所以XmlTextReader使程序开发者更能选择性处理数据。下面一个简单的例子:
Code
1string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Books><Book SN=\"1000\" Name=\".Net\" /><Book SN=\"2000\" Name=\"Java\"/></Books>";
2
3 StringBuilder sb = new StringBuilder();
4
5 using (XmlReader xmlReader = XmlTextReader.Create(new StringReader(xmlStr)))
6 {
7 while (xmlReader.Read())
8 {
9 switch (xmlReader.NodeType)
10 {
11 case XmlNodeType.Element:
12 if (xmlReader.Name == "Book")
13 {
14 if (xmlReader.HasAttributes)
15 {
16 if (xmlReader.MoveToAttribute("SN"))
17 {
18 sb.Append(xmlReader.ReadContentAsInt());
19 }
20 if (xmlReader.MoveToAttribute("Name"))
21 {
22 sb.AppendFormat(" {0}", xmlReader.ReadContentAsString());
23 }
24
25 sb.Append("\r\n");
26 }
27 }
28 break;
29 }
30 }
31 }
32
33 Console.WriteLine(sb.ToString());
34
35 Console.ReadLine();
1string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Books><Book SN=\"1000\" Name=\".Net\" /><Book SN=\"2000\" Name=\"Java\"/></Books>";
2
3 StringBuilder sb = new StringBuilder();
4
5 using (XmlReader xmlReader = XmlTextReader.Create(new StringReader(xmlStr)))
6 {
7 while (xmlReader.Read())
8 {
9 switch (xmlReader.NodeType)
10 {
11 case XmlNodeType.Element:
12 if (xmlReader.Name == "Book")
13 {
14 if (xmlReader.HasAttributes)
15 {
16 if (xmlReader.MoveToAttribute("SN"))
17 {
18 sb.Append(xmlReader.ReadContentAsInt());
19 }
20 if (xmlReader.MoveToAttribute("Name"))
21 {
22 sb.AppendFormat(" {0}", xmlReader.ReadContentAsString());
23 }
24
25 sb.Append("\r\n");
26 }
27 }
28 break;
29 }
30 }
31 }
32
33 Console.WriteLine(sb.ToString());
34
35 Console.ReadLine();