Linq to xml 读取xml元素的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using System.Xml.Linq;


namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string s1 = @"<root><a><b><c>1</c><d>gsdgs</d></b><b><c>dgd</c><d>gsdgs</d></b><b><c>2</c><d>gsdgs</d></b></a></root>";
            List<XElement> ls = getElements(s1, "a", "b");
        }

        private List<XElement> getElements(string sXml, string sReadToFollowingXmlNode, string sXmlNode)
        {
            List<XElement> dlist = new List<XElement>();
            StringReader StrStream = new StringReader(sXml);

            XmlReaderSettings xmlSettings = new XmlReaderSettings();
            xmlSettings.IgnoreWhitespace = true;

            using (System.Xml.XmlReader xmlRead = System.Xml.XmlReader.Create(StrStream, xmlSettings))
            {
                bool flg = true;
                xmlRead.MoveToContent();
                xmlRead.ReadToFollowing(sReadToFollowingXmlNode);//ReadToDescendant,ReadToFollowing 
                while (flg)
                {

                    if (xmlRead.NodeType == XmlNodeType.Element && sXmlNode.Trim().ToUpper() == xmlRead.LocalName.Trim().ToUpper())
                    {
                        XElement e = XElement.ReadFrom(xmlRead) as XElement;
                        dlist.Add(e);

                    }
                    else
                    {
                        flg = xmlRead.Read();
                    }
                }//end while 
            }//end using 

            return dlist;
        }

    }

   
}

posted @ 2011-12-19 16:29  太平洋的风  阅读(395)  评论(0编辑  收藏  举报