日期:2014-05-18 浏览次数:20968 次
private void button1_Click(object sender, EventArgs e) { XmlDocument ParaDoc = new XmlDocument(); ParaDoc.Load(@"D:\test.xml"); XmlNodeReader ParaReader = new XmlNodeReader(ParaDoc); TreeNode tn = new TreeNode(); tn.Text = "Document"; treeView1.Nodes.Add(tn); GetTreeFromXml(ParaReader, tn); } private void GetTreeFromXml(XmlNodeReader pr, TreeNode tn) { TreeNode newTn = new TreeNode(); while(pr.Read()) { switch (pr.NodeType) { case XmlNodeType.XmlDeclaration: case XmlNodeType.Comment: newTn.Text = pr.NodeType.ToString() + ":" + pr.Value ; tn.Nodes.Add(newTn); break; case XmlNodeType.Text: newTn.Text = pr.Value; tn.Nodes.Add(newTn); break; case XmlNodeType.EndElement: tn = tn.Parent; break; case XmlNodeType.Element: if(!pr.IsEmptyElement) { newTn.Text=pr.Name; tn.Nodes.Add(newTn); if(pr.HasAttributes) { for(int i=0;i<pr.AttributeCount;i++) { pr.MoveToAttribute(i); newTn.Text=newTn.Text+","+pr.Name+"="+pr.Value; } } tn=newTn; } else { newTn.Text="EmptyElement:"+pr.Name; if(pr.HasAttributes) { for(int i=0;i<pr.AttributeCount;i++) { pr.MoveToAttribute(i); newTn.Text=newTn.Text+","+pr.Name+"="+pr.Value; } tn.Nodes.Add(