C# 写XML例子--根据行政代码树生成XML

时间:2021-12-05 13:41:42

//填充一个子项

private void FillOneTreeview(TreeNode PNode, XmlElement element)

{

    int num = element.ChildNodes.Count;

    for (int i = 0; i < num; i++)

    {

        XmlElement xnode = element.ChildNodes[i] as XmlElement;

        string objName = xnode.GetAttribute("cantonname");

        string objid = xnode.GetAttribute("cantoncode");

 

        TreeNode Node = new TreeNode(objName);

        Node.Tag = objid;

        PNode.Nodes.Add(Node);

 

        if (element.HasChildNodes)

        {

            FillOneTreeview(Node, xnode);

            //填子

        }

 

    }

}

private void button2_Click(object sender, EventArgs e)

{

    XmlDocument xmlDoc = new XmlDocument();

    string fileName = @"C:/cantoncode.xml";

 

    xmlDoc.Load(fileName);

    //得到顶层节点列表

    XmlNodeList topM = xmlDoc.DocumentElement.ChildNodes;

    foreach (XmlElement element in topM)

    {

        string objName = element.GetAttribute("cantonname");

        string objid = element.GetAttribute("cantoncode");

        TreeNode Node = new TreeNode(objName);

 

        this.treeView1.Nodes.Add(Node);

        Node.Tag = objid;

        if (element.HasChildNodes)

        {

            FillOneTreeview(Node, element);

            //填子

        }

 

        //测试 闫磊 Email:Landgis@126.com,yanleigis@21cn.com 2006.10.11

 

    }

}