1

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);

1 Answer 1

2

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)
            )
      );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.