首页 > 解决方案 > 无法在 C# 中读取 XML 节点

问题描述

我正在为我的工作场所创建一个知识库,当我单击 .NET 表单列表框中的名称时,该名称将依次填充多个文本框。

但是,当单击更改被强制执行时,它不会在 Windows MessageBox 中显示任何数据。我已经测试了 Windows MessageBox 以确保正在启动更改

String client_file_location = @"REDACTED UNC PATH"; // Clients

            XmlDocument config = new XmlDocument();

            FileInfo config_file = new FileInfo(client_file_location);
            config.Load(client_file_location);

            string selected_item = client_list_box.Text;


            XDocument xml = XDocument.Load(client_file_location);

            var nodes = (from n in xml.Descendants("clients")
                         where n.Element("client").Attribute("client_name").Value == selected_item
                         select new
                         {
                             Company = (string)n.Element("Company").Value,
                             knowledge = (string)n.Element("Knowledge").Value
                         }).ToList();

            foreach(var n in nodes) 
            {
                System.Windows.Forms.MessageBox.Show(n.Company);
                new_client_name.Text = n.Company;
                knowledge_base_location.Text = n.knowledge;
            }
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Configuration File for Empired Program: The Curator-->
<clients>
  <client client_name="Test #1">
    <Company>Test #1</Company>
    <Knowledge>http://test.location/</Knowledge>
    <ClientFile>Test #1.xml</ClientFile>
  </client>
</clients>

它应该填写“new_client_name”和“knowledge_base_location”框,但没有输入任何内容

标签: c#xmlwinforms

解决方案


尝试以下:

           var nodes = (from n in xml.Descendants("client")
                         where (string)n.Attribute("client_name") == selected_item
                         select new
                         {
                             Company = (string)n.Element("Company"),
                             knowledge = (string)n.Element("Knowledge")
                         }).ToList();

推荐阅读