C#读取xml文件数据。显示在datagridview控件问题

图片说明

如上图所示框起来的是xml文件的一个子节点内容,这个子节点中包括了不同结构的子节点数据。可以仔细看下这个xml结构,现在我想把这个节点的数据按照下面的格式显示在文本框以及datagridview中。其他同等节点类似,具体代码该怎么写呢?

图片说明

xml文件下载地址

9个回答

图片说明

ccc9149
未知昵称 问题点已经提在下面的回答里面了
大约 2 年之前 回复
ccc9149
未知昵称 https://pan.baidu.com/s/16NtlWAcWncW-Sl3MfzeOLQ 有问题的代码
大约 2 年之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复ccc9149: 代码传网盘或者贴在下面回答的区域里面
大约 2 年之前 回复
ccc9149
未知昵称 怎么获取到Serviceinterfaces下 METHODS节点的内容。。改了你的程序, public NodeCollections Children02 { get { var sub = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "ARGUMENTS"); if (sub == null) sub = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "METHODS"); return new NodeCollections(sub); } } public bool MoveNext()这个在报错??
大约 2 年之前 回复
ccc9149
未知昵称 自己改好了
大约 2 年之前 回复
ccc9149
未知昵称 var root1 = new Node(doc.ChildNodes[1].ChildNodes[1].ChildNodes[1].ChildNodes[1].ChildNodes[0]);能找到xml文件中的Tuner,但是怎么把Tuner下的节点添加到treeview中呢?试了好几个。没写对
大约 2 年之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 回复ccc9149: private void LoadTV(TreeNode tn) 这个方法是加载treeview的,你根据tn判断下,如果到了某一层,你就return而不继续加载就可以了。
大约 2 年之前 回复
ccc9149
未知昵称 在左侧的treeview中不显示图片中框出来的子节点,例如不显示SRdsSettingInit下面的子节点sw_rds_ta 、sw_rds_pty等,怎么改一下你的代码?右边的datagridview中还是按照现在正常显示内容
大约 2 年之前 回复

图片说明

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Q694896
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Form1(XmlNode pnode) : this()
        {
            parentNode = pnode;
            if (this.Height > 160)
            {
                this.Height -= 40;
                this.Width -= 60;
            }
        }

        string clickme = "click me";

        XmlNode parentNode;

        class DataItem
        {
            public string ShortName { get; set; }
            public string Category { get; set; }
            public string BaseTypeRef { get; set; }
            public object Node { get; set; }
            public DataItem(string a, string b, string c)
            {
                ShortName = a;
                Category = b;
                BaseTypeRef = c;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<DataItem> data = new List<DataItem>();
            IEnumerable<XmlNode> nodes;
            if (parentNode == null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(@"TunerServiceInterface.arxml");
                nodes = doc.GetElementsByTagName("IMPLEMENTATION-DATA-TYPE").Cast<XmlNode>();
            }
            else
            {
                nodes = parentNode.ChildNodes.Cast<XmlNode>().Where(x => x.Name == "IMPLEMENTATION-DATA-TYPE-ELEMENT");
                try
                {
                    textBox1.Text = "";
                    textBox2.Text = "";
                    textBox1.Text = parentNode.ParentNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SHORT-NAME").InnerText;
                    textBox2.Text = parentNode.ParentNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY").InnerText;
                }
                catch { }
            }
            foreach (XmlNode node in nodes)
            {
                string sn = "";
                try
                {
                    sn = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SHORT-NAME").InnerText;
                    var c = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY").InnerText;
                    var btf = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SW-DATA-DEF-PROPS").InnerText;
                    data.Add(new DataItem(sn, c, btf) { Node = node });
                }
                catch
                {
                    if (node.ChildNodes.Cast<XmlNode>().Any(x => x.Name == "SUB-ELEMENTS"))
                    {
                        data.Add(new DataItem(sn, clickme, "") { Node = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SUB-ELEMENTS") });
                    }
                }
            }
            dataGridView1.DataSource = data;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex <= 0) return;
            string s = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            if (s == clickme)
            {
                //var f = new Form1((XmlNode)dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Rows[e.RowIndex].Cells.Count - 1].Value);
                //f.StartPosition = FormStartPosition.CenterParent;
                //f.ShowDialog();
                this.parentNode = (XmlNode)dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Rows[e.RowIndex].Cells.Count - 1].Value;
                Form1_Load(this, null);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string s = null;
            try
            {
                this.parentNode = this.parentNode.ParentNode.ParentNode;
                s = parentNode.ParentNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY").InnerText;
            }
            catch
            {
                this.parentNode = null;
            }
            Form1_Load(this, null);
        }
    }
}

caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 稍等,知道你的意思了
大约 2 年之前 回复

图片说明

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Q694896
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Form1(XmlNode pnode) : this()
        {
            parentNode = pnode;
            if (this.Height > 160)
            {
                this.Height -= 40;
                this.Width -= 60;
            }
        }

        string clickme = "click me";

        XmlNode parentNode;

        class DataItem
        {
            public string ShortName { get; set; }
            public string Category { get; set; }
            public string BaseTypeRef { get; set; }
            public object Node { get; set; }
            public DataItem(string a, string b, string c)
            {
                ShortName = a;
                Category = b;
                BaseTypeRef = c;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<DataItem> data = new List<DataItem>();
            IEnumerable<XmlNode> nodes;
            if (parentNode == null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(@"TunerServiceInterface.arxml");
                nodes = doc.GetElementsByTagName("IMPLEMENTATION-DATA-TYPE").Cast<XmlNode>();
            }
            else
            {
                nodes = parentNode.ChildNodes.Cast<XmlNode>().Where(x => x.Name == "IMPLEMENTATION-DATA-TYPE-ELEMENT");
                textBox1.Text = parentNode.ParentNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SHORT-NAME").InnerText;
                textBox2.Text = parentNode.ParentNode.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY").InnerText;
            }
            foreach (XmlNode node in nodes)
            {
                string sn = "";
                try
                {
                    sn = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SHORT-NAME").InnerText;
                    var c = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY").InnerText;
                    var btf = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SW-DATA-DEF-PROPS").InnerText;
                    data.Add(new DataItem(sn, c, btf) { Node = node });
                }
                catch
                {
                    if (node.ChildNodes.Cast<XmlNode>().Any(x => x.Name == "SUB-ELEMENTS"))
                    {
                        data.Add(new DataItem(sn, clickme, "") { Node = node.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SUB-ELEMENTS") });
                    }
                }
            }
            dataGridView1.DataSource = data;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string s = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            if (s == clickme)
            {
                var f = new Form1((XmlNode)dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Rows[e.RowIndex].Cells.Count - 1].Value);
                f.StartPosition = FormStartPosition.CenterParent;
                f.ShowDialog();
            }
        }
    }
}
ccc9149
未知昵称 你仔细看下我提的需求,我不需要弹出新的窗口,显示数据,你看下我在datagridview里面数据是怎么把xml的内容填进去的
大约 2 年之前 回复
caozhy
贵阳老马马善福专业维修游泳池堵漏防水工程 另外几列你按照shortname和category的类似的做,就可以了。
大约 2 年之前 回复
 namespace Q694896
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 18);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(56, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "shortname";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(74, 15);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(133, 20);
            this.textBox1.TabIndex = 1;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(230, 18);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(51, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "catregory";
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(287, 15);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(133, 20);
            this.textBox2.TabIndex = 3;
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(14, 50);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(733, 390);
            this.dataGridView1.TabIndex = 4;
            this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(759, 452);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.DataGridView dataGridView1;

    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;

namespace Q695201
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"TunerServiceInterface.arxml");
            var root = new Node(doc.ChildNodes[1].ChildNodes[1].ChildNodes[0].ChildNodes[1].ChildNodes[1]);
            TreeNode tn = new TreeNode() { Text = root.ShortName, Tag = root };
            treeView1.Nodes.Add(tn);
            LoadTV(tn);
            treeView1.ExpandAll();
            treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
            treeView1.SelectedNode = tn;
        }

        void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            Node node = e.Node.Tag as Node;

            textBox1.Text = node.ShortName;
            textBox2.Text = node.Category;
            List<DGVItem> list = new List<DGVItem>();
            foreach (Node n in node.Children)
            {
                DGVItem item = new DGVItem();
                item.shortname = n.ShortName;
                item.category = n.Category;
                Node n1 = n.Children.Cast<Node>().FirstOrDefault();
                if (n1 != null)
                {
                    item.shortname1 = n1.ShortName;
                    item.category1 = n1.Category;
                    item.arraysize = n1.ArraySuze;
                    item.arraysizesemantic = n1.ArraySizeSemantic;
                    item.basetyperef = n1.BaseTypeRef;
                }
                list.Add(item);
            }
            DataGridView dgv = new DataGridView();
            dgv.Dock = DockStyle.Fill;
            panel1.Controls.Clear();
            panel1.Controls.Add(dgv);
            dgv.DataSource = list;
        }

        private void LoadTV(TreeNode tn)
        {
            Node n = tn.Tag as Node;
            if (n != null)
            {
                foreach (Node item in n.Children)
                {
                    TreeNode tn1 = new TreeNode() { Text = item.ShortName, Tag = item };
                    tn.Nodes.Add(tn1);
                    LoadTV(tn1);
                }
            }
        }
    }

    class Node
    {
        private XmlNode _base;

        public Node(XmlNode baseNode)
        {
            _base = baseNode;
        }

        public NodeCollections Children
        {
            get
            {
                var sub = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SUB-ELEMENTS");
                if (sub == null)
                    sub = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "ELEMENTS");
                return new NodeCollections(sub);
            }
        }

        public string ShortName
        {
            get
            {
                var node = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SHORT-NAME");
                if (node != null) return node.InnerText; else return "";
            }
        }

        public string Category
        {
            get
            {
                var node = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "CATEGORY");
                if (node != null) return node.InnerText; else return "";
            }
        }

        public string BaseTypeRef
        {
            get
            {
                var node = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "SW-DATA-DEF-PROPS");
                if (node != null) return node.InnerText; else return "";
            }
        }

        public string ArraySuze
        {
            get
            {
                var node = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "ARRAY-SIZE");
                if (node != null) return node.InnerText; else return "";
            }
        }
        public string ArraySizeSemantic
        {
            get
            {
                var node = _base.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name == "ARRAY-SIZE-SEMANTICS");
                if (node != null) return node.InnerText; else return "";
            }
        }
    }

    class NodeCollections : IEnumerable<Node>, IEnumerator<Node>, IEnumerator
    {
        private XmlNode _base;

        private XmlNode _itl;

        public NodeCollections(XmlNode basenode)
        {
            _base = basenode;
            Reset();
        }

        public IEnumerator<Node> GetEnumerator()
        {
            return this;
        }

        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this;
        }

        public Node Current
        {
            get { return new Node(_itl); }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            if (_base == null) return false;
            if (_itl == null && _base.FirstChild != null)
            {
                _itl = _base.FirstChild;
                return true;
            }
            if (_itl.NextSibling != null)
            {
                _itl = _itl.NextSibling;
                return true;
            }
            return false;
        }

        public void Reset()
        {
            _itl = null;
        }
    }

    class DGVItem
    {
        public string shortname { get; set; }
        public string category { get; set; }
        public string shortname1 { get; set; }
        public string category1 { get; set; }
        public string arraysize { get; set; }
        public string arraysizesemantic { get; set; }
        public string basetyperef { get; set; }
    }
}

大概看了下
public NodeCollections Children
{
get
{
var sub = _base.ChildNodes.Cast().FirstOrDefault(x => x.Name == "SUB-ELEMENTS");
if (sub == null)
sub = _base.ChildNodes.Cast().FirstOrDefault(x => x.Name == "ELEMENTS");
return new NodeCollections(sub);
}
}
如果你要加载Tuner,这里要加上EVENTS
if (sub == null)
sub = _base.ChildNodes.Cast().FirstOrDefault(x => x.Name == "EVENTS");
就写在Children的subelements后面

ccc9149
未知昵称 caozhy 大佬人不在吗??求解决bug。
大约 2 年之前 回复
ccc9149
未知昵称 添加methods的时候,因为methods下也嵌套了子节点,错误提示见下面的图
大约 2 年之前 回复
ccc9149
未知昵称 看下面的图片,events这样写 没问题。加载methdos内容,想把子节点内容显示在datagridview中,代码跳到421行有问题
大约 2 年之前 回复
ccc9149
未知昵称 我是Tuner下面的events 和 methods都可以加载在treeview中,我尝试可以在datagridview中加载events节点下内容,但是尝试想在datagridview中加载methods节点内容,但是代码307行我自己写的,有问题。
大约 2 年之前 回复

图片说明 @caozhy

图片说明

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐