通过树形结构在控制台显示XML文档的全部内容

xml 文件为:

<?xml version="1.0"?>
<configuration>
 <configSections>
  <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
 </configSections>
 <connectionStrings>
  <add name="cnblogsDb" connectionString="Data Source=192.168.0.88;Initial Catalog=cnblogs;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <appSettings/>
 <system.web>
  <compilation debug="false">
   <assemblies>
    <add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
    <add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
   </assemblies>
  </compilation>
  <authentication mode="Windows"/>
 </system.web>
</configuration>

 

.cs文件代码为:

/*
 * 通过树形结构在控制台显示XML文档的全部内容
 */

using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;

namespace displayxmlDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Xml.XmlDocument doc = new XmlDocument();

           
            //  解析xml 文件,可以通过文件名,字节流,或者字符流获取
            doc.Load("..\\..\\xmlfile1.xml");
            //doc.Load(new System.IO.FileStream("http://www.cnblogs.com/xmlfile1.xml",
            //    System.IO.FileMode.Open));
            //doc.Load(new System.IO.StreamReader("http://www.cnblogs.com/xmlfile1.xml"));

            ShowNode(doc, 0);
        }

        private static void ShowNode(XmlNode node, int spacecount)
        {
            Space(spacecount);

            //输出节点本身
            Console.WriteLine("Name:{0},Type :{1},Value:{2}", node.Name,
                node.NodeType,
                node.Value);

            //判断是否元素,处理元素的属性
            if (node.NodeType == XmlNodeType.Element)
            {
                XmlElement element = node as XmlElement;
                foreach (XmlAttribute att in element.Attributes)
                {
                    ShowNode(att, spacecount + 2);
                }
            }

            Console.WriteLine("-----------------------------------------");

            //处理孩子节点
            foreach (XmlNode n in node.ChildNodes)
            {
                ShowNode(n, spacecount + 5);
            }
        }

        private static void Space(int count)
        {
            for (int i = 0; i < count; i++)
            {
                Console.Write(i);
            }
        }
    }
}

posted @ 2010-06-23 18:01  JasonNET  阅读(1586)  评论(0编辑  收藏  举报