用来自XML文件的组合数据填充组合框

时间:2018-09-25 14:54:21

标签: c# xml linq combobox

我有一个像这样的XML文件:

<?xml version="1.0"?>
<ArrayOfToolClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ToolClass>
    <ToolID>1</ToolID>
    <ToolName>Multiflute Endmill</ToolName>
    <ToolDia>8</ToolDia>
    <ToolTooth>4</ToolTooth>
    <ToolApmxs>32</ToolApmxs>
    <ToolCuttingSpeed>150</ToolCuttingSpeed>
    <ToolFeedPerTooth>0.04</ToolFeedPerTooth>
    <ToolAe>8</ToolAe>
    <ToolAp>4</ToolAp>
    <ToolManufacturer>SECO</ToolManufacturer>
    <ToolSerial>DKFLJDSKJ</ToolSerial>
  </ToolClass>
  <ToolClass>
    <ToolID>2</ToolID>
    <ToolName>Multiflute Endmill</ToolName>
    <ToolDia>4</ToolDia>
    <ToolTooth>4</ToolTooth>
    <ToolApmxs>25</ToolApmxs>
    <ToolCuttingSpeed>235</ToolCuttingSpeed>
    <ToolFeedPerTooth>0.03</ToolFeedPerTooth>
    <ToolAe>4</ToolAe>
    <ToolAp>0.4</ToolAp>
    <ToolManufacturer>SECO</ToolManufacturer>
    <ToolSerial>DJFKLSL</ToolSerial>
  </ToolClass>
</ArrayOfToolClass>

我想将数据填充到组合框:

displaymember= <TooDia>"x"<ToolApmxs>" mm - "<ToolName>;
valuemember=<ToolID>;

我尝试了以下代码:

var xmlDocument = XDocument.Load(@"data\tools.xml");
var toolist = xmlDocument.Descendants("ToolClass");

但是如何将数据合并为指定格式?

谢谢!

2 个答案:

答案 0 :(得分:0)

因此,您可以使用类似的方法获取第一个成员的内部文本:

2018-09-25 11:02:33 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections
2018-09-25 11:02:33 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing connections idle longer than 60000 MILLISECONDS
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing connections idle longer than 60000 MILLISECONDS
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing connections idle longer than 60000 MILLISECONDS
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing connections idle longer than 60000 MILLISECONDS
2018-09-25 11:02:38 [idle_connection_reaper] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections

答案 1 :(得分:0)

var toolist = xmlDocument.Descendants("ToolClass")
    .Select(tc => new
    {
        Display = tc.Element("ToolDia").Value + " x " + tc.Element("ToolApmxs").Value + " mm - " + tc.Element("ToolName").Value,
        Value = tc.Element("ToolID").Value
    })
    .ToList();

comboBox.DisplayMember = "Display";
comboBox.ValueMember = "Value";
comboBox.DataSource = toolist;