蓝派网(www.lan27.com)-精选网络资源,分享和交流! 文章首页站内搜索在线手册广告代码酷站欣赏万年历
您现在的位置: 蓝派网 >> 文章中心 >> 网络编程 >> .NET >> c#(Csharp) >> 正文

用C#读取XML的元素和属性

作者:佚名    文章来源:网络    更新时间:2007-5-30 15:39:49
 <?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);
        }
    }
}


发表评论】【打印此文】【关闭窗口】【点击数:
★好玩的休闲小游戏★