Share via


Convert XML tag into List C#

Question

Tuesday, February 21, 2017 2:40 AM

hi Everyone,

how to convert XML tag into List.

ex, <tag1>Value1</tag1><tag2>Value2</tag2><tag3>Value3</tag3>

List should look like -->

List Item 1 = tag1, Value1

List Item 2 = tag2, Value2

List Item 3 = tag3, Value3

......................... and so on.....

but the tag string "tag1" or "tag2" or "tag3" are dynamic or not known.

is there any generic function which can solve this.

thanks,

Amol

All replies (2)

Tuesday, February 21, 2017 7:49 AM ✅Answered

You can parse the xml string as XDocument and then loop through it and get each tag element name and it's value like:

string MyXml = @"<content>
                   <tag1>Value1</tag1>
           <tag2>Value2</tag2>
           <tag3>Value3</tag3>
         </content>";

XDocument XDocument = XDocument.Parse(MyXml);

var Filtered = XDocument.Root.DescendantNodes().OfType<XElement>();
        
        
        foreach(var item in Filtered)
        {
            Console.WriteLine("Tag: "+item.Name +", Value: "+item.Value);
        }

You can see the working demo fiddle at following link:

https://dotnetfiddle.net/DoFReg

Also see at this post for reference:

http://stackoverflow.com/questions/847978/c-sharp-how-can-i-get-all-elements-name-from-a-xml-file

Hope it helps!


Wednesday, February 22, 2017 6:01 AM ✅Answered

Hi amolsaraf79,

According to your description, as far as I know, you could get all child element of XML file. then get the element name and element InnerText,

save them in the list and loop through all value of the list.

Sample Code:

 protected void Button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<book>" +
                        "<bk>1-861001-57-5</bk>" +
                        "<title>Pride And Prejudice</title>" +
                        "</book>");

            XmlNode root = doc.FirstChild;
            var list = new List<Tuple<string, string>>();
            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                list.Add(new Tuple<string, string>(root.ChildNodes[i].Name, root.ChildNodes[i].InnerText));
            }
             foreach (var item in list)
            {
                Response.Write(item.Item1+ "&nbsp;&nbsp;&nbsp;&nbsp;" + item.Item2+"<br/>");
            }
        }

Best Regards,

Eric Du