XML练习题

<1>LinktoXML

代码namespace LinktoXML
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.创建一个XML文档    
            XDocument XDoc = new XDocument();
            //2.添加根节点  XElement 元素
            XElement XRoot = new XElement("Root");   //需要写入根节点名
            XDoc.Add(XRoot);
            //创建一个省加入到Root中
            XElement xProvince = new XElement("Province");
            XRoot.Add(xProvince);
            //创建省名,位置,省会加入到xProvince中
            XElement xName = new XElement("Name");
            XElement xLocation = new XElement("Location");
            XElement xPcaptial = new XElement("Captial");
            xName.Value = "江苏";
            xLocation.Value = "东部";
            xPcaptial.Value = "南京";
            xProvince.Add(xName, xLocation, xPcaptial);
            //为 xProvince添加属性
            XAttribute xNum = new XAttribute("ID", "001");
            xProvince.Add(xNum);
            //保存XML文档
            XDoc.Save(@"F:\myxml.xml");
        }
    }
}


<2>XML序列化

代码namespace XML序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> perList = new List<Person>()
            {
                new Person(){ Name="董超 ",Age=19, Gender='男'},
                new Person(){ Name="周杰伦",Age=30, Gender='男'},
                new Person(){ Name="蔡依林",Age=28, Gender='女'}
            };
            using (FileStream file =
                new FileStream("序列化xml.xml", FileMode.Create, FileAccess.Write))
            {
                XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
                ser.Serialize(file, perList);
            }
        }
    }
    [Serializable]
    public class Person
    {
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        char gender;

        public char Gender
        {
            get { return gender; }
            set { gender = value; }
        }
        public Person()
        {
        }
    }
}
posted on 2012-07-08 15:10 张磊(Avraber) 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zhanglei-net/archive/2012/07/08/2581563.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值