// ReadXml.cs
// XmlReader示例
using System;
using System.Xml;
class Test
{
public static void Main( string [] args)
{
string path = @"G:\资料\C#面向对象编程\C#面向对象编程\CSharp\Chapter17\books.xml" ;
XmlReader reader = null ;
try
{
// 创建XmlReaderSettings对象
XmlReaderSettings settings = new XmlReaderSettings();
// 设置XmlReaderSettings对象的属性
settings.ProhibitDtd = false ;
// 使用XmlReaderSettings对象来创建XmlReader对象
reader = XmlReader.Create(path, settings);
ReadXml(reader);
reader.Close();
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null )
reader.Close();
}
}
private static void ReadXml(XmlReader reader)
{
try
{
// 解析文件,并显示每一个节点
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.IsEmptyElement) // 空元素?
{
Console.WriteLine( "<{0}/>" , reader.Name);
}
else
{
Console.Write( "<{0}" , reader.Name);
if (reader.HasAttributes) // 属性?
{
while (reader.MoveToNextAttribute())
{
Console.Write( " {0}=\"{1}\"" , reader.Name, reader.Value);
}
}
Console.WriteLine( ">" , reader.Name);
}
break ;
case XmlNodeType.Text:
Console.WriteLine(reader.Value);
break ;
case XmlNodeType.CDATA:
Console.WriteLine( "<![CDATA[{0}]]>" , reader.Value);
break ;
case XmlNodeType.ProcessingInstruction:
Console.WriteLine( "<?{0} {1}?>" , reader.Name, reader.Value);
break ;
case XmlNodeType.Comment:
Console.WriteLine( "<!--{0}-->" , reader.Value);
break ;
case XmlNodeType.XmlDeclaration:
Console.WriteLine( "<?xml version=‘1.0‘?>" );
break ;
case XmlNodeType.Document:
break ;
case XmlNodeType.DocumentType:
Console.WriteLine( "<!DOCTYPE {0} [{1}]>" , reader.Name, reader.Value);
break ;
case XmlNodeType.EntityReference:
Console.WriteLine(reader.Name);
break ;
case XmlNodeType.EndElement:
Console.WriteLine( "</{0}>" , reader.Name);
break ;
}
}
}
catch (XmlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
|