select particular field from an xml file

Posted by Klbaiju under Regular Expressions on 10/27/2010 | Points: 10 | Views : 1558 | Status : [Member] | Replies : 2
Hi friends this is my xml file


<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<Id>100</Id>
<Name>arun</Name>
<Dept>Electrical</Dept>
<dtdate>12-05-2010 </dtdate>
</Employee>
<Employee>
<Id>101</Id>
<Name>Aji</Name>
<Dept>Computer</Dept>
<dtdate>13-05-2010 </dtdate>
</Employee>
<Employee>
<Id>102</Id>
<Name>Kiran</Name>
<Dept>civil</Dept>
<dtdate>14-05-2010 </dtdate>
</Employee>

</Employees>


i want to display records of employee with id=100.


i tried this example

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("Employee.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlDoc.SelectNodes("//Employees//Employee[Id='100']"));


but showing error


Error 1 The best overloaded method match for 'System.Data.DataSet.ReadXml(System.Xml.XmlReader)' has some invalid arguments


Error 2 Argument '1': cannot convert from 'System.Xml.XmlNodeList' to 'System.Xml.XmlReader'


Iam looking for everyone's help

Regards

Baiju




Responses

Posted by: Lalji_mer on: 10/27/2010 [Member] Bronze | Points: 25

Up
0
Down
you can try this link for sample code.

http://forums.asp.net/t/1239928.aspx

LP MER

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Raouf on: 10/27/2010 [Member] Starter | Points: 25

Up
0
Down
Try something like this :

XDocument doc = XDocument.Load(@"E:\test.xml");

IEnumerable<XElement> elements = doc.Root.Elements(XName.Get("Employee")).Where(o=>o.Element(XName.Get("Id")).Value.Equals("100"));
foreach (XElement item in elements)
{
Console.WriteLine(item);
}


There some little things to take in account for this sample to work on all cases :
the most simple one to guess is that you need to change the path from where the xml file is loaded.

The second is that the code works with LINQ to XML so it needs this namespace : System.Xml.Linq.

The last one is that every xml file has namespace, or should; so if it's the case with your file you will need to process the XElements with the relative namespace.

A simple way to do this is the following :
string nameSpace = doc.Root.Name.Namespace;
and in every XName.Get call pass the nameSpace varialbe as the second parameter; the first one is the local name : "Employee", "Id"...

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response