XML数据分析函数 c# LINQUTOXML

 /// <summary>
    /// 函数结构体
    /// </summary>

public class Xmlcontrol
    {
        public string nodename;
        public Xmlcontrol xc;
        public Xmlcontrol(string nodename, Xmlcontrol childrenname)
        {
            this.nodename = nodename;
            xc = childrenname;
        }
        public Xmlcontrol()
        {

        }
    }

/// <summary>
    /// 数据实体类
    /// </summary>

public  class SendShowObject
    {
        public SendShowObject()
        {

        }
        public string imageurl;
        public string nagiveteurl;
    }
public  class MyXmlAPIcontrol
    {
        public MyXmlAPIcontrol()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">请求xml文件的地址</param>
        /// <param name="filts">需要删选的数据</param>
        /// <param name="MainDATA">主要数据的父节点</param>
        /// <param name="dataname">数据节点的名字</param>
        /// <returns></returns>
        public static List<SendShowObject> Xmlcontrol(string url, Xmlcontrol[] filts, Xmlcontrol MainDATA,string dataname)
        {
            List<SendShowObject> so = new List<SendShowObject>();
            XElement xEle = XElement.Load(url);
            XElement TheTop = GetValueFrom(MainDATA,xEle);
            XElement[] cc = TheTop.Elements(dataname).ToArray();
            foreach (XElement xm in cc)
            {
                so.Add(new SendShowObject { imageurl = GetValueFrom(xm, filts[0]), nagiveteurl = GetValueFrom(xm, filts[1]) });
            }
            return so;
        }

        private static XElement GetValueFrom(Xmlcontrol xc, XElement xe)
        {
            try
            {
                if (xc.nodename == null) return xe;
                XElement XmlNode = xe.Element(xc.nodename);
                if (xc.xc != null)
                {
                    return GetValueFrom(xc.xc, XmlNode);
                }
                return XmlNode;
            }
            catch (System.Exception ex)
            {

            }
            return null;
        }

        private static string GetValueFrom(XElement xe, Xmlcontrol xc)
        {
            try
            {

                if (xc.nodename == null) return null;
                
                if (xc.xc != null)
                {
                    XElement XmlNode = xe.Element(xc.nodename);
                    return GetValueFrom(XmlNode, xc.xc);
                }
                return xe.Attribute(xc.nodename).Value.ToString();
            }
            catch (System.Exception ex)
            {
                try { return  xe.Value.ToString(); } catch(System.Exception){}
            }
            return null;
        }
    }

 

posted on 2012-08-11 09:30  56851240  阅读(155)  评论(0编辑  收藏  举报