编程语言

img zhuo_chang

用TreeView显示XML文件的结构

发表于2004/9/28 18:23:00  1085人阅读

 

这个程序是我第一次作用.NET操纵XML. 它的目的是用TreeView控件把XML文件的结构显示出来.

请看下面的程序:

 

private void FillTree(XmlNode node, TreeNodeCollection parentnode)
{
	// End recursion if the node is a text type
	if(node == null || node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA)
		return;

	TreeNodeCollection tmptreenodecollection = AddNodeToTree(node, parentnode);

	// Add all the children of the current node to the treeview
	foreach(XmlNode tmpchildnode in node.ChildNodes)
	{
		FillTree(tmpchildnode, tmptreenodecollection);
	}
}

private TreeNodeCollection AddNodeToTree(XmlNode node, TreeNodeCollection parentnode)
{
	TreeNode newchildnode = CreateTreeNodeFromXmlNode(node);

	// if nothing to add, return the parent item
	if(newchildnode == null) return parentnode;

	// add the newly created tree node to its parent
	if(parentnode != null) parentnode.Add(newchildnode);

	return newchildnode.Nodes;
}

private TreeNode CreateTreeNodeFromXmlNode(XmlNode node)
{
	TreeNode tmptreenode = new TreeNode();

	if((node.HasChildNodes) && (node.FirstChild.Value != null))
	{
		tmptreenode = new TreeNode(node.Name);
		TreeNode tmptreenode2 = new TreeNode(node.FirstChild.Value);
		tmptreenode.Nodes.Add(tmptreenode2);
	}
	else if(node.NodeType != XmlNodeType.CDATA) 
	{
		tmptreenode = new TreeNode(node.Name);
	}

	return tmptreenode;
}
 
阅读全文
0 0

相关文章推荐

img
取 消
img