.net中XML编程总结

190 篇文章 6 订阅


一 载入XML文件到树视图

代码;

string filepath = Environment.CurrentDirectory + "\\K\\SqlServerZt\\" + "FAMILY2.xml";
            

            try
            {
                // SECTION 1. Create a DOM Document and load the XML data into it.
                XmlDocument dom = new XmlDocument();
                dom.Load(filepath);


                // SECTION 2. Initialize the TreeView control.
                treeView1.Nodes.Clear();
                treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = treeView1.Nodes[0];


                SECTION 3. Populate the TreeView with the DOM nodes.
                AddNode(dom.DocumentElement, tNode);
                treeView1.ExpandAll();
            }
            catch (XmlException xmlEx)
            {
                MessageBox.Show(xmlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList nodeList;
            int i;


            // Loop through the XML nodes until the leaf is reached.
            // Add the nodes to the TreeView during the looping process.
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[i];
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                inTreeNode.Text = (inXmlNode.OuterXml).Trim();
            }
        }


XML文件中都是英文载入正常;



含有中文会出现如下错误提示:





正确载入一个含有中文的XML文档到树视图:



该文档如下:

<?xml version="1.0" encoding="gb2312" ?>
<!DOCTYPE 家庭[
<!ELEMENT 家庭 (人+)>
<!ELEMENT 人 EMPTY>
<!ATTLIST 人
    relID ID #REQUIRED
    parentID IDREFS #IMPLIED
    name CDATA #REQUIRED
>
]>
<家庭>
    <人 relID="P_1" name="爸爸"/>
    <人 relID="P_2" name="妈妈"/>
    <人 relID="P_3" parentID="P_1 P_2" name="儿子"/>
</家庭>


不过有时用记事本打开该文件,编辑其节点为别的中文内容,保存后再载入又会出错;应该说加了 encoding="gb2312"  可以识别中文;所以此问题尚未完全解决;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值