【问题标题】:How to read xml to combobox in datagrid?如何将 xml 读取到数据网格中的组合框?
【发布时间】:2017-12-16 06:28:19
【问题描述】:

我正在尝试将 xml 文件读取到数据集,并将数据集绑定到数据网格

XML 文件:

<NewDataSet>
    <Communications>
        <ModelNumber>1</ModelNumber>
        <ParamName>BaudRate</ParamName>
        <ParamValues>
            <ParamValue>9600</ParamValue>
            <ParamValue>19200</ParamValue>
            <ParamValue>115200</ParamValue>
        </ParamValues>
        <DefaultValue>19200</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
    </Communications>
    <Communications>
        <ModelNumber>1</ModelNumber>
        <ParamName>Parity</ParamName>
        <ParamValues>
            <ParamValue>None</ParamValue>
            <ParamValue>Odd</ParamValue>
            <ParamValue>Even</ParamValue>
        </ParamValues>
        <DefaultValue>None</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
    </Communications>
        <Communications>
        <ModelNumber>1</ModelNumber>
        <ParamName>StopBit</ParamName>
        <ParamValues>
           <ParamValue>1</ParamValue>
           <ParamValue>2</ParamValue>
        </ParamValues>
        <DefaultValue>1</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
    </Communications>
    <Communications>
        <ModelNumber>1</ModelNumber>
        <ParamName>DataBit</ParamName>
        <ParamValues>
           <ParamValue>7</ParamValue>
           <ParamValue>8</ParamValue>
        </ParamValues>
        <DefaultValue>8</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
   </Communications>
   <Communications>
        <ModelNumber>1</ModelNumber>
        <ParamName>SlaveAddress</ParamName>
        <ParamValues>
            <ParamValue>1</ParamValue>
        </ParamValues>
        <DefaultValue>1</DefaultValue>
        <MaxValue>247</MaxValue>
        <MinValue>1</MinValue>
   </Communications>
</NewDataSet>

将 xml 读取到数据集:

    public ObservableCollection<Communication> GetCommunications()
    {
        DataSet ds = new DataSet();
        ds.ReadXml("Communications.xml");
        ObservableCollection<Communication> communications = new ObservableCollection<Communication>();
        foreach (DataRow communicationRow in ds.Tables["Communications"].Rows)
        {
            var c = new Communication((ushort)Convert.ToInt16(communicationRow["ModelNumber"]), communicationRow["ParamName"].ToString(),
                    ds.Tables["ParamValue"].Rows[0][0].ToString(), communicationRow["DefaultValue"].ToString(), communicationRow["MaxValue"].ToString(),
                    communicationRow["MinValue"].ToString());
            foreach (DataRow dr in ds.Tables["ParamValue"].Rows)
            {
                c.ParamValues.Add(dr[0].ToString());
            }
            communications.Add(c);
        }
        return communications;
    }

绑定数据网格:

    <DataGridTemplateColumn Header="ParamValues">                                              
       <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                 <ComboBox ItemsSource="{Binding ParamValues}" SelectedItem="{Binding DefaultValue}" />
            </DataTemplate>                                                           
       </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

但是上面的代码运行时出现错误,组合框ParamValues 的每一列都有每个表Communications Image detail 的所有ParamValue,您能告诉我如何解决这个问题吗?提前谢谢!

【问题讨论】:

  • ReadXml 在这种情况下不会很好地工作。你嵌套的标签太深了。第一级标记是数据集名称。第二级标记是 DataTable 名称。第三级标签是列名,内部文本是行数据。您有 4 个级别的标签,因此 ReadXml 生成了多个数据表。部分数据在表 0 中,其他部分数据在表 1 中。您可能希望绑定到表 1 而不是表 0。
  • 谢谢,我想你的答案很接近了。当我调试GetCommunications() 类时,我发现它返回communications 和所有Commucations 表中的所有ParamValue,但我不知道如何修改这个GetCommunications() 类。你能帮我吗?
  • 一旦ReadXml创建了多个表,通常合并表并不简单。使用自定义代码解析 xml 通常比使用 ReadXml 更容易。
  • 这种情况下应该如何解析xml?

标签: c# xml wpf combobox datagrid


【解决方案1】:

试试下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            DataTable dt = new DataTable("Communications");

            string[] columnNames = doc.Descendants("ParamName").Select(x => (string)x).Distinct().ToArray();

            dt.Columns.Add("ModelNumber", typeof(string));
            foreach (string colName in columnNames)
            {
                dt.Columns.Add(colName, typeof(string));
            }

            var models = doc.Descendants("Communications").GroupBy(x => (string)x.Element("ModelNumber")).ToList();

            foreach(var model in models)
            {
                var orderedModel = model.Select(x => new { 
                    paramCount = x.Descendants("ParamValue").Count(), 
                    parmName = (string)x.Element("ParamName"),
                    parms = x.Descendants("ParamValue").Select(y => (string)y).ToList()
                }).OrderByDescending(x => x.paramCount).ToList();

                for (int parm = 0; parm < orderedModel.FirstOrDefault().paramCount; parm++)
                {
                    DataRow newRow = dt.Rows.Add();
                    newRow["ModelNumber"] = model.Key;
                    foreach(var col in orderedModel)
                    {
                        if (col.paramCount > parm)
                        {
                            newRow[col.parmName] = col.parms[parm];
                        }
                    }


                }
            }
        }
    }
}

【讨论】:

  • 感谢您的回答,由于我使用的是 WPF,您应该以这种方式绑定到 datagrid 组合框吗?
  • 就像使用任何 DataTable 一样。 Sajeetharan 代码现在应该可以与我的 DataTable 一起使用了。
【解决方案2】:

将DataSet 替换为XDocument:

public ObservableCollection<Communication> GetCommunications()
{
    ObservableCollection<Communication> communications = new ObservableCollection<Communication>();
    XDocument doc = XDocument.Load("Communications.xml");
    foreach (XElement communicationRow in doc.Root.Elements("Communications"))
    {
        var c = new Communication((ushort)Convert.ToInt16(communicationRow.Element("ModelNumber").Value), communicationRow.Element("ParamName").Value,
                communicationRow.Element("DefaultValue").Value, communicationRow.Element("DefaultValue").Value, communicationRow.Element("MaxValue").Value,
                communicationRow.Element("MinValue").Value);

        foreach (XElement paramValue in communicationRow.Element("ParamValues").Elements())
        {
            c.ParamValues.Add(paramValue.Value);
        }

        communications.Add(c);
    }

    return communications;
}

【讨论】:

  • 我认为这是解决这个问题的最好方法。非常感谢!
猜你喜欢
  • 2017-12-08
  • 2014-03-01
  • 2021-02-16
  • 2019-11-02
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
相关资源
最近更新 更多