Загрузка...

Add the attribute in XML which are created from Database using C# | Part 4

Add the attribute in XML which are created from Database using C#:
Requirement: visual studio 2015 or any other version, SQL server 2012 or upper version.
Benefits:
XML supports information exchange between computer systems such as websites, databases, and third-party applications.
C# Code to create XML from database:
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HSSNFCU;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=1234");
string sql = "SELECT a.empid,emp_name,salary,emp_city,b.Department_name from Employee A inner join [employee_deparment] B on a.empid=b.empid";

// Create a new DataSet
DataSet ds = new DataSet();

// Create a SqlDataAdapter
SqlDataAdapter da = new SqlDataAdapter(sql, con);

// Fill the DataSet
da.Fill(ds, "employeedetails");
// Create an XmlDocument
XmlDocument xmlDoc = new XmlDocument();

// Create the root element
XmlElement root = xmlDoc.CreateElement("employeedetails");
xmlDoc.AppendChild(root);

// Get the DataTable from the DataSet

DataTable dataTable = ds.Tables["employeedetails"];

// Iterate through each DataRow and create XML elements
foreach (DataRow row in dataTable.Rows)
{
// Create an employee element
XmlElement employee = xmlDoc.CreateElement("employee");
root.AppendChild(employee);

// addding the attributes
XmlAttribute xat = xmlDoc.CreateAttribute("Department_name");
xat.InnerText= row["Department_name"].ToString();
employee.Attributes.Append(xat);

// Create and append child elements
XmlElement empid = xmlDoc.CreateElement("empid");
empid.InnerText = row["EmpId"].ToString();
employee.AppendChild(empid);

XmlElement empName = xmlDoc.CreateElement("emp_name");
empName.InnerText = row["emp_name"].ToString();
employee.AppendChild(empName);

XmlElement salary = xmlDoc.CreateElement("salary");
salary.InnerText = row["Salary"].ToString();
employee.AppendChild(salary);

XmlElement empCity = xmlDoc.CreateElement("emp_city");
empCity.InnerText = row["emp_city"].ToString();
employee.AppendChild(empCity);
}

// Show the XML in a text BOX
TextBox1.Text = xmlDoc.InnerXml.ToString();


xmlDoc.Save(@"F:\Project-Library\XML\data_with_attribite.xml");

Видео Add the attribute in XML which are created from Database using C# | Part 4 канала Syed Ali
Страницу в закладки Мои закладки
Все заметки Новая заметка Страницу в заметки

На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.

Об использовании CookiesПринять