Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to read particular record from xml file through id of that record using C#.net
Posted
Comments
lukeer 1-Oct-12 2:44am    
What have you tried so far?
What problems / errors did you encounter?

I'd start with the XmlDocument[^] class and read through MSDN's articles and examples from there.
Sandeep Mewara 1-Oct-12 2:56am    
And the issue is?

1 solution

For example, Consider the following XML file,

XML
<?xml version="1.0" encoding="utf-8"?>
<Records>
  <Record>
    <RecordID>8119</RecordID>
    <ID>AM5715</ID>
    <LastUpdated>09/06/2011 10:21:53</LastUpdated>
  </Record>
  <Record>
    <RecordID>111</RecordID>
    <ID>AM5716</ID>
    <LastUpdated>09/06/2011 10:11:29</LastUpdated>
  </Record>
  <Record>
    <RecordID>8121</RecordID>
    <ID>AM5717</ID>
    <LastUpdated>21/06/2011 10:39:40</LastUpdated>
  </Record>
  <Record>
    <RecordID>8123</RecordID>
    <ID>AM5718</ID>
    <LastUpdated>19/01/2012 13:24:00</LastUpdated>
  </Record>
  <Record>
    <RecordID>8126</RecordID>
    <ID>AM5719</ID>
    <LastUpdated>29/03/2006 16:21:21</LastUpdated>
  </Record>
  <Record>
    <RecordID>8127</RecordID>
    <ID>AM5720</ID>
    <LastUpdated>19/01/2012 13:24:27</LastUpdated>
  </Record>
</Records>


We are now looking for the xml record with rec_id = "111"

Enumerate through the XML file and read one by one,

C#
//This is the main method, or the calling function,
string rec_id="111";

//Call the function to get the xml record for matching rec_id
XElement MatchingRecord= GetMatchingXML(rec_id);


C#
private XElement GetMatchingXML(string RecID)
{
   XElement MatchingXML = null;

//Get the enumerator to traverse through each xml record  in the XML file
   IEnumerable <XElement> Records=
                        from el in XML.Elements("Record")
                        select el;

//Now traverse through each  xml record and look for matching rec_id
   foreach (XElement record in Records)
   {

//Check if the provided rec_id is matching with the recId fro this particular xml record 
      if (RecID.Equals(record .Descendants("rec_id").FirstOrDefault().Value.ToString()))
      {

//if matching, return this xml record
          MatchingXML = record ;
          break;
      }
    }
        
    return MatchingXML;
}


This code will return the following XML file,

XML
<Record>
    <RecordID>111</RecordID>
    <ID>AM5716</ID>
    <LastUpdated>09/06/2011 10:11:29</LastUpdated>
  </Record>


Try this and ask me if you have any questions.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900