如何从文件读取 XML(完整例程)

此示例阐释如何使用 XmlTextReader 类从文件读取 XML。

1.新建一个c#空web项目,默认名称为WebProject1

2.在WebProject1下添加新项web窗体,命名为ReadXmlFile.aspx,代码为:

<%@ Page Language="C#" CodeBehind="ReadXmlFile.cs" Debug="true" Inherits="WebProject1.ReadXmlFile"%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="HowTo.Samples.XML" %>

<script language="C#" runat=server>

private void SubmitBtn_Click(Object sender, EventArgs e)
{
  StringWriter writer = new StringWriter();
  Console.SetOut(writer);
  ReadXmlFileSample myReadXmlFileSample = new ReadXmlFileSample();
  myReadXmlFileSample.Run(Server.MapPath("books.xml"));
  output.InnerHtml = writer.ToString();
}

</script>

<html>
<head>

        <link rel="stylesheet" href="intro.css">
</head>
<body style="background-color:f6e4c6">

         <form action="ReadXmlFile.aspx" method="post" runat="server">
         <font>输入文件:</font>
        <a href="/WebProject1/books.xml">books.xml</a>
  <center>
    &nbsp;&nbsp;&nbsp;&nbsp;<asp:button type=submit text="运行" OnClick="SubmitBtn_Click" runat="server"/></br>
         </form>
  </center>
  <p>

  <table align="center">
  <tr><th>读取文件时的输出...</th><tr>
  <tr><th><span></span></th></tr>
  <tr><td><h4><xmp id="output" runat="server"/></h4></td></tr>
  </table>

</body>
</html>

 

添加新项代码文件,命名为ReadXmlFile.cs,代码为:

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();
    }

} // 结束类 ReadXmlFileSample
} // 结束命名空间 HowTo.Samples.XML
 

添加新项XML文件,命名为books.xml,代码为:

<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>
3,在浏览器中查看ReadXmlFile.aspx。
相关解释文件在:http://chs.gotdotnet.com/QuickStart/howto/default.aspx?url=/quickstart/howto/doc/Xml/ReadXMLFile.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值