对于任意的XML的遍历

王朝other·作者佚名  2008-05-30
窄屏简体版  字體: |||超大  

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

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航