【问题标题】:Reading XML with different names to Combobox C#将具有不同名称的 XML 读取到 Combobox C#
【发布时间】:2020-07-17 12:36:34
【问题描述】:

我对 c# 很陌生,似乎无法找到正确的答案

我有以下 xml 结构(元素数量不同)

<config>
<extras>
<dir_update>C:\extension\update.exe</dir_update>
</extras>
<connection_MAIN>
<ip>LOCALHOST,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>gzqs=</password>
</connection_MAIN>
<connection_LOBBY>
<ip>10.0.0.2,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
<caixa>5yIz5GPu80s=</caixa>
<printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
</connection_LOBBY>
<connection_FRONT>
<ip>10.0.0.5,1433</ip>
<bd>FIELDS</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
</connection_FRONT>
</config>

我已经在我的组合框中获得了以“connection_”开头的元素,当我在组合框中选择连接时,我想要&lt;ip&gt;&lt;bd&gt;&lt;user&gt;&lt;password&gt; 中的值。

我遇到的问题是它返回的是单词本身而不是下面代码中的值

private void Form1_Load(object sender, EventArgs e)
        {
            using(DataSet ds = new DataSet())
            {
                ds.ReadXml(textBox1.Text);
                foreach(DataTable dt in ds.Tables)
                {
                    if (dt.ToString().Contains("conection_"))
                    {
                        comboBox1.Items.Add(dt.ToString().Replace("conection_", ""));
                    }
                }
                comboBox1.SelectedIndex = 0;
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            using(DataSet ds = new DataSet())
            {
                ds.ReadXml(textBox1.Text);
                string v = comboBox1.Text.ToString();
                string ip = ds.Tables[$"conection_{v}"].Columns[0].ToString();
            }
        }

在本例中,当我选择组合框中的第一个选项时,变量 ip 正在获取值“ip”并且我想要“LOCALHOST,1433”。

我还想按名称(“ip”、“bd”)搜索列值,但我似乎只在使用 Columns[0]、Columns[1] 时才能得到结果。

我遵循了一些我环顾四周的指南,但它们似乎不适用于这种 xml 格式,或者我看错了。

感谢任何帮助。

【问题讨论】:

    标签: c# xml datatable combobox dataset


    【解决方案1】:

    不需要使用DataSetDataTable 数据类型。处理 XML 的最佳 API 是 LINQ to XML

    在下面查看。

    c#

    void Main()
    {
        const string MAIN = "connection_MAIN";
        string IP = string.Empty;
        string bd = string.Empty;
        string user = string.Empty;
        string password = string.Empty;
    
        XElement xml = XElement.Parse(@"<config>
        <extras>
            <dir_update>C:\extension\update.exe</dir_update>
        </extras>
        <connection_MAIN>
            <ip>LOCALHOST,1433</ip>
            <bd>DATA</bd>
            <user>sa</user>
            <password>gzqs=</password>
        </connection_MAIN>
        <connection_LOBBY>
            <ip>10.0.0.2,1433</ip>
            <bd>DATA</bd>
            <user>sa</user>
            <password>I/wqqZIgzqs=</password>
            <caixa>5yIz5GPu80s=</caixa>
            <printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
        </connection_LOBBY>
        <connection_FRONT>
            <ip>10.0.0.5,1433</ip>
            <bd>FIELDS</bd>
            <user>sa</user>
            <password>I/wqqZIgzqs=</password>
        </connection_FRONT>
    </config>");
    
        // get needed connection fragment
        IEnumerable<XElement> fragment = xml.Descendants(MAIN);
    
        // get all needed elements one by one
        IP = fragment.Elements("ip")?.FirstOrDefault().Value;
        bd = fragment.Elements("bd")?.FirstOrDefault().Value;
        user = fragment.Elements("user")?.FirstOrDefault().Value;
        password = fragment.Elements("password")?.FirstOrDefault().Value;
    }
    

    【讨论】:

      【解决方案2】:

      使用 Xml Linq 将结果放入数据表中

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Xml;
      using System.Xml.Linq;
      using System.Data;
      
      namespace ConsoleApplication1
      {
          class Program
          {
              const string FILENAME = @"c:\temp\test.xml";
              static void Main(string[] args)
              {
                  DataTable dt = new DataTable();
                  dt.Columns.Add("name", typeof(string));
                  dt.Columns.Add("ip", typeof(string));
                  dt.Columns.Add("bd", typeof(string));
                  dt.Columns.Add("user", typeof(string));
                  dt.Columns.Add("password", typeof(string));
      
                  XDocument doc = XDocument.Load(FILENAME);
      
                  foreach(XElement connection in doc.Descendants().Where(x => x.Name.LocalName.StartsWith("connection_")))
                  {
                      dt.Rows.Add(new object[] {
                          ((string)connection.Name.LocalName).Substring(((string)connection.Name.LocalName).IndexOf("_") + 1),
                          (string)connection.Element("ip"),
                          (string)connection.Element("bd"),
                          (string)connection.Element("user"),
                          (string)connection.Element("password")
                      });
      
      
                  }
                  Dictionary<string, DataRow> dict = dt.AsEnumerable()
                      .GroupBy(x => x.Field<string>("name"), y => y)
                      .ToDictionary(x => x.Key, y => y.FirstOrDefault());
                  string ip = dict["LOBBY"].Field<string>("ip");
      
              }
          }
      }
      

      【讨论】:

      • 恕我直言,OP 需要在 UI 层中使用来自 XML 的数据填充组合框。让我们等待OP的回应。
      • 我只是将结果放入数据表中,就像 OP 试图做的那样。
      • 不错的方法,但是如何从文本框中的“connection_LOBBY”元素(在我的示例中为“10.0.0.2,1433”)获取值?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多