对于任意的XML的遍历

创建日期:2008年1月6日 来自:knowsky 浏览:2492次 作者:匿名

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+"\n");

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

                }
            }

            public static  void NodeOperate(XmlNode xn1)
            {

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

                }
                else
                {
                    Console.Write(xn1.Name + "\n");
                    Console.Write(xn1.InnerText);
                    Console.Write("\n");
                    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 Settings\SKY\My Documents\Visual Studio 2005\Projects\Project1\Project1\system.xml");
            Console.Read();

        }


责编:aoaob
相关搜索: 对于任意的XML的遍历   XML技巧  
Google
嗷嗷毙技术网版权申明:大家可以自由转载我站点的文章,但原作者和来自我站的链接必须保留(非我站原创的,按照原来链接,自行链接)。文章版权归作者所有。
特别注意:本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有,文章若有侵犯作者版权,请与我们联系,我们将立即删除修改。
搜索 
Google