如何从XML中读取数据并在c#的文本框中显示它们?

本文关键字:文本 显示 XML 读取 数据 | 更新日期: 2023-09-27 18:11:35

这是我的XML文件,我想在文本框中输入ID,并在其他文本框中获取其他数据。

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Users>
<User Name="aa" Occupation="dd" Date_Of_Birth="123456" NIC="123123" 
ID="79461" />
<User Name="Ali Rasheed" Occupation="Student" Date_Of_Birth="111694" NIC="4550246607037" ID="12661" />
  <User Name="Asif Rasheed" Occupation="Civil Engineer" Date_Of_Birth="241190" NIC="4550346603073" ID="90939" />
  <User Name="Sadaf Sohail" Occupation="Teacher" Date_Of_Birth="112233" NIC="445566677999" ID="72508" />
  <User Name="Shahnaz Bano" Occupation="Retired Principle" Date_Of_Birth="223311" NIC="454564974149" ID="65199" />
  <User Name="Alex" Occupation="Programmer" Date_Of_Birth="111694" NIC="45522002211447" ID="44534" />
</Users>

这是我的代码

var data = XElement.Load(@"C:'GenesisSolutionsCRMSBuild12101'XMLDatabase.xml").Descendants("User");
foreach (var textbox in Controls.OfType<TextBox>())
{
    var value = data.FirstOrDefault(v => v.Attribute("ID").Value == textbox.Name.Replace("txt", "").ToLower());
    if (value != null)
    {
        textBox1.Text = value.Attribute("Name").Value;
        textBox2.Text = value.Attribute("Occupation").Value;
        textBox3.Text = value.Attribute("Date_Of_Birth").Value;
        textBox4.Text = value.Attribute("NIC").Value;
    }
}

如何从XML中读取数据并在c#的文本框中显示它们?

无需遍历所有控件。这就像从ID文本框中读取Text属性一样简单:

var data = XElement.Load(@"C:'GenesisSolutionsCRMSBuild12101'XMLDatabase.xml")
                   .Descendants("User");
// Get the ID the user entered
string id = idTextBox.Text;
var user = data.FirstOrDefault(v => v.Attribute("ID").Value == id);
if (user != null)
{
    textBox1.Text = user.Attribute("Name").Value;
    textBox2.Text = user.Attribute("Occupation").Value;
    textBox3.Text = user.Attribute("Date_Of_Birth").Value;
    textBox4.Text = user.Attribute("NIC").Value;
}

您可以考虑将textBoxN重命名为更有用的名称,如nameTextBox