实例:使用XmlTextReader类的对象读取XML文档
代码如下
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml; //引入命名空间 7 namespace ReadXmlDemo 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //打开xml 14 XmlTextReader textReader = new XmlTextReader("C:\note.xml"); 15 //读取数据 16 while (textReader.Read()) 17 { 18 textReader.MoveToElement(); 19 Console.WriteLine("XmlTextReader Properties Test"); 20 Console.WriteLine("=============================="); 21 Console.WriteLine("Name:"+textReader.Name); 22 Console.WriteLine("Base URI:"+textReader.BaseURI); 23 Console.WriteLine("Local Name:"+textReader.LocalName); 24 Console.WriteLine("Attribute Count:"+textReader.AttributeCount.ToString()); 25 Console.WriteLine("Line Number:"+textReader.LineNumber.ToString()); 26 Console.WriteLine("Node Type:"+textReader.NodeType.ToString()); 27 Console.WriteLine("Attribute Count:"+textReader.Value.ToString()); 28 } 29 Console.ReadKey(); 30 } 31 } 32 }
运行结果如下:
另外,XML源文件为note.xml
<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>