Reputation: 341
I am building a C# application. I want to insert the following XML data to 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>
Previously I have tried an XML that has not attribute value, But now I want to insert with attribute value.
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);
Upvotes: 1
Views: 54
Reputation: 26856
You should use XAttribute
instead of XElement
in order to insert ID
as attribute:
doc.Root.Add(
new XElement("Employee",
new XAttribute("ID", textBox1.Text),
new XElement("Name", textBox2.Text)
)
);
Upvotes: 2