Asim Zaidi
Asim Zaidi

Reputation: 28344

parsing an xml type string

I have a string like this

<InitParams>
                <myparams>

                  <Ad>true</Ad>
                  <Ay>true</Ay>
                  <Sd>false</Sd>

                </myparams>
                <myContent>

                  <Item>
                      <IM>true</IM>
                      <AL>1234</AL>

                    </Item>

                </myContent>
              </InitParams>

I need the value between the tags <IM> and <AL>. Being new to C# and .net not sure what would be the best way to do it. Read up on xmlDoc and linq but sounds like overkill for this small need.

Upvotes: 1

Views: 301

Answers (1)

Mark W
Mark W

Reputation: 3909

The whole point of something like LINQ to XML was to prevent overkill, because it's so easy to use:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;



 namespace WhateverNamespaceYouWant
 {

    public class Item
    {
        public bool IM { get; set; }
        public int AL { get; set; }
    }
    public class ItemsRepository
    {
        public IEnumerable<Item> GetAllItemsInXML()
        {
            var _items = new List<Item>();
            var doc = XDocument.Load("this");
            // finds every node of Item
            doc.Descendants("Item").ToList()
            .ForEach(item =>
            {
                var myItem = new Item() // your domain type
                {
                    IM = item.Element("IM").Value.ConvertToValueType<bool>(),
                    AL = item.Element("AL").Value.ConvertToValueType<int>(),
                };
                _items.Add(myItem);
            });
            return _items;
        }
    }

    public static class Extensions
    {
        public static T ConvertToValueType<T>(this string str) where T : struct
        {
            try
            {
                return (T)Convert.ChangeType(str, typeof(T));
            }
            catch
            {
                return default(T);
            }
        }
    }

}

Upvotes: 3

Related Questions