在文本框的树视图中显示XML架构数据

时间:2011-06-17 07:07:36

标签: c# xml visual-studio-2010 xsd

我是这个项目的新手。它是在C#的visual studio 2010上。我试图在带有树视图的文本框中显示此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();

1 个答案:

答案 0 :(得分:4)

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,here is a nice demonstration无需重复此处)