Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 13464 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > C# > Filter attribute values from XML file and display the result ...
Niladri.Biswas

Filter attribute values from XML file and display the result

 Code Snippet posted by: Niladri.Biswas | Posted on: 5/11/2012 | Category: C# Codes | Views: 600 | Status: [Member] | Points: 40 | Alert Moderator   


Suppose we have the below XML file

<?xml version="1.0" encoding="UTF-8"?>

<Countries>
<India>
<Player isPlaying="1">
<Name>Z. Tendulkar</Name>
<Age>23</Age>
</Player>
<Player isPlaying="0">
<Name>S. Khan</Name>
<Age>30</Age>
</Player>
</India>
<Australia>
<Player isPlaying="1">
<Name>B. Warne</Name>
<Age>40</Age>
</Player>
<Player isPlaying="1">
<Name>P. Gooch</Name>
<Age>30</Age>
</Player>
</Australia>
</Countries>


We need to display the player information for those players who will play for the game (i.e. isPlaying attribute of Player entity should be 1) for a particular country.

Here is my solution for the same

string countryName = "India";            


string inputXml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<Countries>
<India>
<Player isPlaying=""1"">
<Name>Z. Tendulkar</Name>
<Age>23</Age>
</Player>
<Player isPlaying=""0"">
<Name>S. Khan</Name>
<Age>30</Age>
</Player>
</India>
<Australia>
<Player isPlaying=""1"">
<Name>B. Warne</Name>
<Age>40</Age>
</Player>
<Player isPlaying=""1"">
<Name>P. Gooch</Name>
<Age>30</Age>
</Player>
</Australia>
</Countries>";

XDocument xmlSkuDescDoc = null;
xmlSkuDescDoc = XDocument.Parse(inputXml); // use XDocument.Load(filename) if loading from file

(from data in xmlSkuDescDoc.Descendants(countryName)
select data)
.Descendants("Player")
.Where(el => el.Attribute("isPlaying").Value == "1")
.Elements()
.ToList()
.ForEach(i => Console.WriteLine("{0} {1}",i.Name.ToString(),i.Value));


Output

Name Z. Tendulkar

Age 23


N.B.~ Please add the namespace System.Xml.Linq
Hope this will be useful

Best Regards,
Niladri Biswas
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/19/2013 12:32:59 PM