当前位置:首页 > 网络编程 > WEB编程 > XML编程 > 对于任意的XML的遍历

对于任意的XML的遍历

点击次数:27 次 发布日期:2008-11-21 22:22:37 作者:源代码网
源代码网推荐

class test
        {
            private static string root;

            public static  void showXML(string path)
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(path);
               
                XmlNodeList xnl = xd.DocumentElement.ChildNodes;
                root = xd.FirstChild.NextSibling.Name;//记录根节点

                Console.Write(root+" ");

                foreach (XmlNode xn in xnl)
                {
                    //Console.Write(xn.Attributes["name"].Value.ToString()+" ");
                    XmlNode child = xn.FirstChild;
                   
                    NodeOperate(child);
              

                }
            }

            public static  void NodeOperate(XmlNode xn1)
            {

                if (xn1.HasChildNodes == true)
                {
                    Console.Write(xn1.Name + " ");
                    Console.Write(" ");
                    XmlNode childNode = xn1.FirstChild;
                   
                    NodeOperate(childNode);

                }
                else
                {
                    Console.Write(xn1.Name + " ");
                    Console.Write(xn1.InnerText);
                    Console.Write(" ");
                    if (xn1.NextSibling != null)
                    {
                       
                        NodeOperate(xn1.NextSibling);
                    }
                    else
                    {
                        int flag = 0;
                        while (xn1.NextSibling == null)
                        {
                          
                           
                            if (xn1.Name == root)//检查是否到了根节点,如果不检查会出现节点的引用错误
                            {
                                flag = 1;
                                break;
                            }
                            else
                            {

                                xn1 = xn1.ParentNode;
                            }
                           
                        }
                        if (flag == 0)
                        {
                            NodeOperate(xn1.NextSibling);
                        }
                        else if(flag==1)
                        {
                            Console.Write("End");
                        }
                    }

                   
                }
            }
        }


        public static void Main()
        {
         
            test.showXML(@"C:Documents and SettingsSKYMy DocumentsVisual Studio 2005ProjectsProject1Project1system.xml");
            Console.Read();

        }

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华