最近刚接触XML,买了本书看,发现不是很全面。没有提及怎么读取XML中元素的内容。求教怎么用C#读取XML中的数据,我想用来放进SQL数据库的。高手请指教。谢谢

解决方案 »

  1.   


    参考
    <?xml version="1.0" encoding="gb2312" ?>
    <musiclession>
        <student ID="s101">
            <name>李华</name>
            <age>12</age>
            <score>92</score>
        </student>
        <student ID="s102">
            <name>笑林</name>
            <age>22</age>
            <score>82</score>
        </student>
        <student ID="s103">
            <name>王明</name>
            <age>18</age>
            <score>90</score>
        </student>
    </musiclession>
    using System;
    using System.Xml;namespace DOMTest
    {
        class DOM
        {
            private static void PrintElement(XmlDocument document)
            {
                //获取所有的Node
                XmlNodeList nodeList=document.GetElementsByTagName("*");
                //打印每一个node的名称
                for(int i=0;i<nodeList.Count;i++)
                {
                    XmlNode node=nodeList.Item(i);
                    Console.WriteLine(node.Name);
                }
            }        private static void PrintAttributes(XmlDocument document)
            {
                XmlNodeList nodeList=document.GetElementsByTagName("*");
                XmlNamedNodeMap nameNodeMap;
                XmlElement element;
                XmlAttribute attribute;
                string attributeName;
                string attributeValue;            for(int i=0;i<nodeList.Count;i++)
                {
                    element=(XmlElement)nodeList.Item(i);
                    Console.WriteLine(element.Name+":"+element.ChildNodes[0].Value);
                    nameNodeMap=element.Attributes;
                    if(nameNodeMap!=null)
                    {
                        for(int j=0;j<nameNodeMap.Count;j++)
                        {
                            attribute=(XmlAttribute)nameNodeMap.Item(j);
                            attributeName=attribute.Name;
                            attributeValue=attribute.Value;
                            Console.WriteLine("属性是:"+attributeName+"="+attributeValue);
                        }
                    }
                }
            }
            [STAThread]
            static void Main(string[] args)
            {
                XmlDocument document =new XmlDocument();
                document.Load("student.xml");
                Console.WriteLine("元素是:");
                PrintElement(document);//            Console.WriteLine("元素属性是:");
    //            PrintAttributes(document);
            }
        }
    }
    本文转摘自『蓝派网』http://www.lan27.com/Article/200705/946.htm
      

  2.   

    2楼对我帮助蛮大,但是我好像还是用不上- -||有谁能给个DATASET的例子?
      

  3.   

    C#读取XML的方式 一般采用DOM解析
    XmlDocument去MSDN上查一下这个类的方法就可以了 很简单的
      

  4.   

    DataSet ds = new DataSet();
    ds.ReadXml(@"Your XML File Address");这个就可以,你试试!