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 helpful.
Tags: XDocument , C#