简体   繁体   English

解析xml类型字符串

[英]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> . 我需要标签<IM><AL>之间的值。 Being new to C# and .net not sure what would be the best way to do it. 刚接触C#和.net时,不确定会是最好的方法。 Read up on xmlDoc and linq but sounds like overkill for this small need. 在xmlDoc和linq上阅读有关内容,但对于这种小的需求来说听起来有些矫kill过正。

The whole point of something like LINQ to XML was to prevent overkill, because it's so easy to use: 像LINQ to XML这样的东西的全部要点是防止过度杀伤,因为它非常易于使用:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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