一 载入XML文件到树视图
代码;
string filepath = Environment.CurrentDirectory + "KSqlServerZt" + "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" 可以识别中文;所以此问题尚未完全解决; (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|