TreeView绑定xml数据,递归时“未将对象引用设置到对象的实例”
TreeView绑定xml数据,递归时“未将对象引用设置到对象的实例”!代码如下:
/// <summary>
/// XML填充目标TreeView
/// </summary>
/// <param name="dir_tree">目标TreeView</param>
/// <param name="path">xml路径</param>
public static void BindTree2(TreeView dir_tree, string path)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(path);
XmlElement xroot = xmldoc.DocumentElement;
TreeNode troot = new TreeNode();
troot.Text = xroot.Attributes["name"].Value;
troot.Value = xroot.Attributes["id"].Value;
dir_tree.Nodes.Add(troot);
troot = dir_tree.Nodes[0];
addTreeNode(xroot, troot);//递归
}
private static void addTreeNode(XmlNode xNode, TreeNode tNode)
{
if (xNode.HasChildNodes)//判断是否有子节点
{
XmlNode xNodeChild;//存放xml节点
TreeNode tNodeChild;//存放树节点
XmlNodeList xNodeList = xNode.ChildNodes;//存放节点集合(这里是所有子节点的集合)
for (int i = 0; i <= xNodeList.Count - 1; i++)
{
tNodeChild = new TreeNode();//实例化树节点
xNodeChild = xNode.ChildNodes[i]; //获取当前子节点
tNodeChild.Text = xNodeChild.Attributes["name"].Value;
tNode.ChildNodes.Add(tNodeChild);
tNodeChild = tNode.ChildNodes[i];//获取当前树节点
addTreeNode(xNodeChild, tNodeChild); //递归
}
}
} --------------------编程问答-------------------- 代码抄的吧。
多加个判断 是否 null 就行了。
递归常见的问题, --------------------编程问答--------------------
请问加在哪里呢? --------------------编程问答-------------------- 把你每次递归时的内容打出来。
分析一下。
看看,或者全加是否为null的判断即可。 --------------------编程问答-------------------- if(xNodeList !=null&&xNodeList.Count >0){
for (int i = 0; i <= xNodeList.Count - 1; i++)
{
tNodeChild = new TreeNode();//实例化树节点
xNodeChild = xNode.ChildNodes[i]; //获取当前子节点
tNodeChild.Text = xNodeChild.Attributes["name"].Value;
tNode.ChildNodes.Add(tNodeChild);
tNodeChild = tNode.ChildNodes[i];//获取当前树节点
addTreeNode(xNodeChild, tNodeChild); //递归
}
} --------------------编程问答--------------------
试过了,还是不行呢。 --------------------编程问答-------------------- 像这些也要判段如
if(xNodeChild.Attributes["name"]!=null)
tNodeChild.Text = xNodeChild.Attributes["name"].Value;
补充:.NET技术 , ASP.NET