// Passing variable instead of string for the element
{
...
string firstname = "Satheesh";
string department = "Engineering";
...
new XElement("firstname", firstname),
new XElement("department", department),
...
}
// Get Mobile Number of the employee by calling the method
// GetCurrentMobileNumber()
{
...
new XElement("phone", GetCurrentMobileNumber(),
new XAttribute("type", "mobile"))
...
}
Let's see how to create the XML elements using LINQ query and objects. In this case we have to create the objects. Let's assume that we have a class for having the project details in a department something like this
class Project
{
public string projectName;
public string projectDescription;
public string projectManager;
public int projectHours;
public string[] resourceNames;
}
Create objects from this project class and have couple of projects with an array of resource names who are all working in the project
var Projects = new[] {
new Project {
projectName = "XYZ",
projectDescription = "XYZ R&D project for XLinq",
projectManager = "Sat",
projectHours = 160,
resourceNames = new[] { "Sat", "Kumar", "Martin", "Suresh" }
},
new Project {
projectName = "ABC",
projectDescription = "ABC R&D project for XLinq",
projectManager = "Amir",
projectHours = 120,
resourceNames = new[] { "Ahmed", "Sachin", "Amir", "Salman" }
}
};
Now we can create the XML file from the above project information objects using the XLinq query as
XElement projects =
new XElement("Projects",
from proj in Projects
select new XElement("Project",
new XElement("ProjectName", projectName),
from Res in proj.resourceNames
select new XElement("Resource", Res)
)
);
The output of the above query would be
<Projects>
<Project>
<ProjectName>XYZ</ProjectName>
<ProjectDescription>XYZ R&D project for XLinq</ProjectDescription> <ProjectManager>Sat</ProjectManager> <ProjectHours>160</ProjectHours> <Resource>Sat</Resource>
<Resource>Kumar</Resource>
<Resource>Martin</Resource>
<Resource>Suresh</Resource>
</Project>
<Project>
<ProjectName>ABC</ProjectName>
<ProjectDescription>ABC R&D project for XLinq</ProjectDescription> <ProjectManager>Amir</ProjectManager> <ProjectHours>120</ProjectHours> <Resource>Ahmed</Resource>
<Resource>Sachin</Resource>
<Resource>Amir</Resource>
<Resource>Salman</Resource>
</Project>
</Projects>
XLinq Methods
XLinq provides various methods to easily manipulate the XML Elements and its contents. We can insert, update, delete and copy the contents of XML content. For example you can add a new element to the Employees XML tree with the Add() method. This will be added as the last child. If you want to add the element at the beginning as a first child then you can use the method AddFirst(). You can use AddBeforThis() and AddAfterThis() methods to add the elements before or after any particular Element
// Adding a new element as last child
XElement employeeJoinDate = new XElement("EmployeeJoinDate", "31st Dec 2007");
Employees.Add(employeeJoinDate);
// Adding a new element after an existing element
XElement employeeLastName = new XElement("lastname","Lastname");
XElement firstName = Employees.Element("Employee").Element("firstname");
firstName.AddAfterThis(employeeLastName);
In the above example the employeeLastName element was created without any parent. It means that it does not belong to any tree or it's not the child of any other element. Before adding the new element after the firstName element as firstName.AddAfterThis, you can check the parent property of the employeeLastName object which will return null. This is because the element does not belong to the XML tree and does not come under any parent. It's just an element.
Console.WriteLine(employeeLastName.Parent.Value);
Add this new element after the firstName element of Employee element. Now the parent of new element employeeLastName will be the same as the firstname element as it is added to the same parent of firstname element.
Updating and deleting elements from the XML is similar to adding element to the XML. For example, to remove the firstname element of the Employee element just call Remove() method on the firstname element as below
Employees.Element("Employee").Element("firstname").Remove();
Updating the Element value is also similar to the Add and Remove methods. You can use ReplaceContent() and SetElement() methods to update the content of the element.
Attributes
In the same way we added, deleted and updated the elements, we can also update, delete and add attributes. For example, if you want to update the attribute type of the first phone element from "office" to "Work" then just use the SetAttribute() method of the Element as below.
Employees.Element("Employee").Elements("phone").First().SetAttribute("type", "Work");
We can add a new attribute using the same functional construction method as we did for creating new element. Here we must use the XAttribute instead of XElement.
We can also remove an existing attribute using the method Remove().
Reading from and Writing to Database
Let's take the example of below XML which has details of couple of projects. These details are stored in SQL database and we will see how to get the details as XML and how to post the changes back to the database.
<Products>
<Product>
<ProductID>1160</ProductID>
<CategoryID>15</CategoryID>
<ModelName>KEYBOARD</ModelName>
<UnitCost>INR1500</UnitCost>
<discountPercent>10</discountPercent>
</Product>
<Product>
<ProductID>1165</ProductID>
<CategoryID>15</CategoryID>
<ModelName>Mouse</ModelName>
<UnitCost>INR1200</UnitCost>
<discountPercent>10</discountPercent>
</Product>
</Products>
This XML can be constructed easily by using the LINQ query against the Database. The Query looks something like this.
XElement Products =
new XElement("Products",
from c in <database>.ProductInfo
where c.CategoryID== "15"
select new XElement("ProductID ", c. ProductID),
new XElement("ModelName ", c. ModelName),
new XElement("UnitCost ",c. UnitCost)
new XElement("discountPercent ",c. discountPercent)
)
);
The <database> is the object for connecting to the database and table object. Let's say the XML file which we have created is modified and we have to post the changes back to SQL Server database. For example, the discountPercent of all products has to be updated. To achieve this, we can write a Linq query something like this
foreach (var prod in Products.Elements("Product")) {
ProductInfo pro = <Database>.ProductInfo.
First(c => c.ProductID == (string)prod.Element("ProductID"));
pro.discountPercent = (string)prod.Element("discountPercent");
}
<database>.SubmitChanges();
There are lots of other features which we can make use of for XML programming. This is just an introduction to the features that XLinq provides.