Your XML looks a little bit malformed due to the .
before each tag name; I therefore sanitized your XML code by removing the .
s, and made a solution based on the following XML code:
<SECTIONS>
<SECTION ID ="1" NAME="System Health" CONTROL-TYPE="Button" LINK="http://www.google.co.in/">
<DATAITEMS> </DATAITEMS>
</SECTION>
</SECTIONS>
Thanks to the sanitized XML code, you now can use the following code snippet to achieve what you want (don't forget the using directive using System.Xml.Linq;
):
XDocument doc = XDocument.Parse("<SECTIONS><SECTION ID =\"1\" NAME=\"System Health\" CONTROL-TYPE=\"Button\" LINK=\"http://www.google.co.in/\"><DATAITEMS></DATAITEMS></SECTION></SECTIONS>");
var query = from item in doc.Descendants("SECTIONS").Descendants("SECTION")
select new {
Name = (string)item.Attribute("NAME"),
Id = (string)item.Attribute("ID"),
ControlType = (string)item.Attribute("CONTROL-TYPE"),
Link = (string)item.Attribute("LINK")
};
(Sidenote: You can load your XML code directly from a file (e.g. file.xml
), too, by defining the doc
variable as follows:
XDocument doc = XDocument.Load(@"C:\Path\To\file.xml");
)
The following code will print the value of each attribute:
foreach (var elem in query)
System.Console.WriteLine(string.Format("{0}, {1}, {2}, {3}", elem.Id, elem.Name, elem.ControlType, elem.Link));
Console output:
1, System Health, Button, http://www.google.co.in/