Recently i came across a situation where i was supposed to write code for reading a XML file where the structure of the document was fixed but following information was changing.
1) RootNode text,
2) ParentNode text
3) Number of Child nodes inside the parent node
So in Today's example we will see a way to write customized or generic code to read XML document where the Root Node, Parent Node and number of Child nodes can vary using LINQ.
Customers.xml
<?xml version="1.0" encoding="utf-8" ?>
Happy coding....
1) RootNode text,
2) ParentNode text
3) Number of Child nodes inside the parent node
So in Today's example we will see a way to write customized or generic code to read XML document where the Root Node, Parent Node and number of Child nodes can vary using LINQ.
Customers.xml
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<name>Aryan Mehta</name>
<city>Bangalore</city>
<country>India</country>
</Customer>
<Customer>
<name>Steve Martin</name>
<city>Sydney</city>
<country>Australia</country>
</Customer>
</Customers>
For this example i am using "Customer.xml" as the sample xml file.
//Loading the customers xml into the
XDocument object
XDocument oXDocument = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml");
//Retrieving the Root Node of the xml document dynamically
string RootNodeName =
oXDocument.Root.Name.ToString();
//retrieving all the distinct elements inside a Root
Node
var ElementNodes = oXDocument.Root.DescendantNodes().OfType<XElement>().Select(x
=> x.Name).Distinct();
//ElementNodes.First
will give the first node inside Root Node
//which is nothing but the Parent Node
var CustomerInfo = from
CustomerInfoNode in
oXDocument.Element(RootNodeName).Elements(ElementNodes.First())
select CustomerInfoNode;
//Looping through all the Customers elements in the
CustomerInfo Element
foreach (XElement
oXElement in CustomerInfo)
{
//For separating the customer information
Console.WriteLine("----Customer Information----");
//Looping through Customer details of a
particular Customer
foreach (XElement
oXElementData in oXElement.Elements())
{
//displaying the customer details in the console window
Console.WriteLine(oXElementData.Name.ToString()
+ "=" +
oXElementData.Value.ToString());
}
Console.WriteLine("");
}
Console.ReadLine();
When i use the same code for following "Employees.xml" which is with different Root Node and Parent Node.
Employees.xml
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<name>Aryan Mehta</name>
<city>Bangalore</city>
</ Employee >
< Employee >
<name>Steve Martin</name>
<city>Sydney</city>
</ Employee >
</ Employees >
So the code of today's example can be used with different XML document having dynamic Root Node and Parent Node. But the only restriction is that the structure of the XML node should be same.
I hope this example has served the purpose of giving an idea on how to read a XML document in a generic way using LINQ.
Happy coding....
Comments
Post a Comment