【问题标题】:Get the content of a child node from the parent selected by the listbox从列表框选择的父节点获取子节点的内容
【发布时间】:2018-08-17 19:11:07
【问题描述】:

我会问你是否可以执行以下任务:

这是我的 xml 文件:

<SETTING_LIST>
    <setting>
      <name>first</name>
      <enable>the command...</enable>
      <disable>the command...</disable>
      <check>the command...</check>
      <word>first</word>
      <ifchecktrue>true</ifchecktrue>
      <usegrep>true</usegrep>
    </setting>
   <setting>
      <name>second</name>
      <enable>the command...</enable>
      <disable>the command...</disable>
      <check>the command...</check>
      <word>first</word>
      <ifchecktrue>true</ifchecktrue>
      <usegrep>true</usegrep>
    </setting>
  </SETTING_LIST>

所以用户将从列表框中选择父节点的名称,例如“first”或“second”,而不是我需要将内容作为子节点的字符串返回给我的东西。我尝试了类似的方法,但它不起作用。

private void checkbtn_Click(object sender, EventArgs e)
        {
            string selectednode = Convert.ToString(listBox1.SelectedItem);
            string prompt;

            XmlDocument doc = new XmlDocument();
            doc.Load("dati.txt");

            XmlNode node = doc.SelectSingleNode("setting/" + selectednode + "/check");
            prompt = node.InnerText;

            MessageBox.Show(prompt);
        }

感谢您的帮助!!

【问题讨论】:

    标签: c# xml visual-studio


    【解决方案1】:

    使用 xml linq:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq ;
    
    
    namespace ConsoleApplication1
    {
        public class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            public static void Main()
            {
                XDocument doc = XDocument.Load(FILENAME);
                string name = "first";
    
                Dictionary<string, string> dict = doc.Descendants("setting")
                    .Where(x => (string)x.Element("name") == name).FirstOrDefault()
                    .Elements().GroupBy(x => x.Name.LocalName, y => (string)y)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
    
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多