使用 Linq 问题将数据从 C# 插入到 XML?

Insert data from C# to XML with using Linq issue?

我正在构建 C# 应用程序。我想将以下 XML 数据插入到 XML.

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee ID="1">
       <Name>Numeri</Name>
  </Employee>
  <Employee ID="2">
    <Name>Ismail</Name>
  </Employee>
  <Employee ID="3">
    <Name>jemu</Name>
  </Employee>
</Employees>

之前我试过没有属性值的XML,但是现在我 想插入属性值。

string _file = (Application.StartupPath+"/employees.xml");
XDocument doc;

if (!File.Exists(_file))
{
    doc = new XDocument();
    doc.Add(new XElement("Employees"));
}
else
{
    doc = XDocument.Load(_file);
}

doc.Root.Add(
      new XElement("Employee",
                   new XElement("ID", textBox1.Text),
                   new XElement("Name", textBox2.Text)
            )
      );
doc.Save(_file);

您应该使用 XAttribute 而不是 XElement 以便将 ID 作为属性插入:

doc.Root.Add(
      new XElement("Employee",
                   new XAttribute("ID", textBox1.Text),
                   new XElement("Name", textBox2.Text)
            )
      );