日期:2014-05-18 浏览次数:20823 次
XmlTextWriter tw; public void WriteXML(TreeNodeCollection tc) { foreach (TreeNode Node in tc) { WriteOneXML(Node); WriteXML(Node.Nodes); tw.WriteEndElement(); } } private void WriteOneXML(TreeNode Node) { string objid = Node.Tag.ToString(); string objName = Node.Text; tw.WriteStartElement("cantoncode" + (Node.Level + 1)); tw.WriteAttributeString("cantoncode", objid); tw.WriteAttributeString("cantonname", objName); } private void button3_Click(object sender, EventArgs e) { string fileName = @"C:/cantoncode.xml"; tw = new XmlTextWriter(fileName, null); tw.Formatting = Formatting.Indented; tw.WriteStartDocument(); tw.WriteStartElement("cantoncode"); WriteXML(treeView1.Nodes); tw.WriteEndElement(); tw.WriteEndDocument(); tw.Flush(); tw.Close(); }
------解决方案--------------------
最简单的把 TreeNode.Text 保存为 Xml 节点名的例子
// 方法 private static void TreeToXml(TreeNodeCollection tree, XmlDocument xmlDoc, XmlNode xml) { foreach (TreeNode item in tree) { XmlNode node = xml.AppendChild(xmlDoc.CreateElement(item.Text)); TreeToXml(item.Nodes, xmlDoc, node); } } // 调用 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null)); XmlNode root = xmlDoc.AppendChild(xmlDoc.CreateElement("root")); TreeToXml(某TreeView.Nodes, xmlDoc, root); xmlDoc.Save("保存路径");