C# 读xml例子

2009年1月26日星期一

C# 读xml例子





The Autobiography of Benjamin Franklin

Benjamin
Franklin

8.99


The Confidence Man

Herman
Melville

11.99


The Gorgias

Plato

9.99



namespace HowTo.Samples.XML
{

using System;
using System.IO;
using System.Xml;

public class ReadXmlFileSample
{
private const string document = "books.xml";

public static void Main()
{
ReadXmlFileSample myReadXmlFileSample = new ReadXmlFileSample();
myReadXmlFileSample.Run(document);
}

public void Run(String args)
{
XmlTextReader reader = null;

try
{
// 用 XmlTextReader 加载文件
Console.WriteLine ("正在读取文件 {0} ...", args);
reader = new XmlTextReader (args);
Console.WriteLine ("已成功读取文件 {0} ...", args);

// 处理所提供的 XML 文件
Console.WriteLine ("正在处理 ...");
Console.WriteLine ();
FormatXml(reader, args);
}
catch (Exception e)
{
Console.WriteLine ("未能读取文件 {0}", args);
Console.WriteLine ("异常:{0}", e.ToString());
}

finally
{
Console.WriteLine();
Console.WriteLine("对文件 {0} 的处理已完成。", args);
// 通过 XmlTextReader 完成
if (reader != null)
reader.Close();
}
}

private static void FormatXml (XmlReader reader, String filename)
{
int declarationCount=0, piCount=0, docCount=0, commentCount=0, elementCount=0, attributeCount=0, textCount=0, whitespaceCount=0;

while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.XmlDeclaration:
Format (reader, "XmlDeclaration");
declarationCount++;
break;
case XmlNodeType.ProcessingInstruction:
Format (reader, "ProcessingInstruction");
piCount++;
break;
case XmlNodeType.DocumentType:
Format (reader, "DocumentType");
docCount++;
break;
case XmlNodeType.Comment:
Format (reader, "Comment");
commentCount++;
break;
case XmlNodeType.Element:
Format (reader, "Element");
elementCount++;
if (reader.HasAttributes)
attributeCount += reader.AttributeCount;
break;
case XmlNodeType.Text:
Format (reader, "Text");
textCount++;
break;
case XmlNodeType.Whitespace:
whitespaceCount++;
break;
}
}

// 显示该文件的统计信息。
Console.WriteLine ();
Console.WriteLine("{0} 文件的统计信息", filename);
Console.WriteLine ();
Console.WriteLine("Xml 声明:{0}",declarationCount++);
Console.WriteLine("处理指令:{0}",piCount++);
Console.WriteLine("文档类型:{0}",docCount++);
Console.WriteLine("注释:{0}",commentCount++);
Console.WriteLine("元素:{0}",elementCount++);
Console.WriteLine("属性:{0}",attributeCount++);
Console.WriteLine("文本:{0}",textCount++);
Console.WriteLine("空白:{0}",whitespaceCount++);
}

private static void Format(XmlReader reader, String nodeType)
{
// 格式化输出
Console.Write(reader.Depth + " ");
Console.Write(reader.AttributeCount + " ");
for (int i=0; i < reader.Depth; i++)
{
Console.Write('\t');
}

Console.Write(reader.Prefix + nodeType + "<" + reader.Name + ">" + reader.Value);

// 显示当前节点的属性值
if (reader.HasAttributes)
{
Console.Write(" 属性:");

for (int j=0; j < reader.AttributeCount; j++)
{
Console.Write(" [{0}] " + reader[j], j);
}
}
Console.WriteLine();
}

0 评论:

发表评论