在树视图中的文本框中显示XML架构数据
本文关键字:XML 数据 显示 文本 视图 | 更新日期: 2023-09-27 17:59:17
我是这个项目的新手。它在C#的visualstudio2010上。我试图在一个带有树视图的文本框中显示这个XML模式。我很难把它做成树景。
DataSet dsM= new DataSet("M"); string filePath = @"C:'Documents and Settings'Administrator'Desktop'M.xsd"; dsM.ReadXml(filePath); System.IO.StringWriter swXML = new System.IO.StringWriter(); dsM.WriteXmlSchema(swXML); textBox.Text = swXML.ToString();
using System;
using System.Windows.Forms;
using System.Xml;
public class XmlTreeDisplay : System.Windows.Forms.Form{
private System.Windows.Forms.TreeView treeXml = new TreeView();
public XmlTreeDisplay() {
treeXml.Nodes.Clear();
this.Controls.Add(treeXml);
// Load the XML Document
XmlDocument doc = new XmlDocument();
string filePath = @"C:'Documents and Settings'Administrator'Desktop'M.xsd";
try {
doc.Load(filePath);
}catch (Exception err) {
MessageBox.Show(err.Message);
return;
}
ConvertXmlNodeToTreeNode(doc, treeXml.Nodes);
treeXml.Nodes[0].ExpandAll();
}
private void ConvertXmlNodeToTreeNode(XmlNode xmlNode,
TreeNodeCollection treeNodes) {
TreeNode newTreeNode = treeNodes.Add(xmlNode.Name);
switch (xmlNode.NodeType) {
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.XmlDeclaration:
newTreeNode.Text = "<?" + xmlNode.Name + " " +
xmlNode.Value + "?>";
break;
case XmlNodeType.Element:
newTreeNode.Text = "<" + xmlNode.Name + ">";
break;
case XmlNodeType.Attribute:
newTreeNode.Text = "ATTRIBUTE: " + xmlNode.Name;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
newTreeNode.Text = xmlNode.Value;
break;
case XmlNodeType.Comment:
newTreeNode.Text = "<!--" + xmlNode.Value + "-->";
break;
}
if (xmlNode.Attributes != null) {
foreach (XmlAttribute attribute in xmlNode.Attributes) {
ConvertXmlNodeToTreeNode(attribute, newTreeNode.Nodes);
}
}
foreach (XmlNode childNode in xmlNode.ChildNodes) {
ConvertXmlNodeToTreeNode(childNode, newTreeNode.Nodes);
}
}
public static void Main(){
Application.Run(new XmlTreeDisplay());
}
}
修改以满足您的需求。。。
(相反,将TreeView转换为XML,这里有一个很好的演示,不需要在这里重复)