Shah Shah - 1 month ago 6
ASP.NET (C#) Question

How to get values from XML file based on Key field in ASP.Net

I'm new to XML. I have a file as below which lists the details of courses.

<?xml version="1.0" encoding="UTF-8"?>
<RESPONSE>
<SINGLE>
<KEY name="courses">
<MULTIPLE>
<SINGLE>
<KEY name="id">
<VALUE>3</VALUE>
</KEY>
<KEY name="category">
<VALUE>6</VALUE>
</KEY>
<KEY name="shortname">
<VALUE>XYZ101</VALUE>
</KEY>
<KEY name="fullname">
<VALUE>BUS101: Introduction </VALUE>
</KEY>
<KEY name="description">
<VALUE>This is a dummy text for description;</VALUE>
</KEY>
</SINGLE>
<SINGLE>
<KEY name="id">
<VALUE>4</VALUE>
</KEY>
<KEY name="category">
<VALUE>7</VALUE>
</KEY>
<KEY name="shortname">
<VALUE>ABC101</VALUE>
</KEY>
<KEY name="fullname">
<VALUE>ABC101: ABC Category</VALUE>
</KEY>
<KEY name="description">
<VALUE>Detailed introduction to the basic principles and methods ;</VALUE>
</KEY>
</SINGLE>
</RESPONSE>


I want to read this file and display the contents as below in asp page, please help. I tried the example from How to read single node value from xml file. But it didn't return any value. My expected output is as below
Id, category, shortname, fullname, description
3, 6 , XYZ101, BUS101: Introduction, This is a dummy text for description
4, 7, ABC101, ABC101: ABC Category, Detailed introduction to ...

Answer

You may give a try to following using XDocument:

XDocument doc = System.Xml.Linq.XDocument.Load(yourXMLFile);
            var ab = doc.Root.Descendants("SINGLE").Descendants("KEY").Descendants("MULTIPLE").Descendants("SINGLE").Select(x => new { values = x.Elements().ToList() }).ToList();
            var newList = ab.Select(y => new
            {
                values = y.values.Select(z =>
                    new
                    {
                        key = z.Attribute("name").Value,
                        value = z.Elements("VALUE").FirstOrDefault().Value
                    }).ToList()
            }).ToList();

It will give you the xml nodes with id, category etc.

Comments