简体   繁体   中英

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.

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);
            }
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM