无法在 C# 中读取 XML 节点
Posted
技术标签:
【中文标题】无法在 C# 中读取 XML 节点【英文标题】:Unable to read XML Nodes in C# 【发布时间】:2020-01-13 21:50:40 【问题描述】:我正在为我的工作场所创建一个知识库,当我单击 .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”框,但没有输入任何内容
【问题讨论】:
【参考方案1】:尝试以下:
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();
【讨论】:
【参考方案2】:只需使用列表尝试序列化概念。 我的示例代码:
//Write XML
List<UO> lstUO = new List<UO>();
using (StreamWriter writer = new StreamWriter(FilePath,false))
XmlSerializer serializer = new XmlSerializer(typeof(List<UO>));
serializer.Serialize(writer, lstUO);
writer.Close();
//Read XML
using (FileStream stream = File.OpenRead(FilePath))
XmlSerializer serializer = new XmlSerializer(typeof(List<UO>));
List<UO> dezerializedList = (List<UO>)serializer.Deserialize(stream);
stream.Close();
public class UO
public string input get; set;
public string input1 get; set;
【讨论】:
以上是关于无法在 C# 中读取 XML 节点的主要内容,如果未能解决你的问题,请参考以下文章