醒着☆☆

H5 Laya Native Game

  博客园 :: 首页 :: 新随笔 :: 联系 :: :: 管理 ::

最近可以重新拾起我的C#,很迫切。
总之是边看书和网上的教程边练习。
因为最近需要做flash修改底层的xml中的数据,
所以迫切需要先把xml的修改来学习

-----------------------------------------

1:插入节点和属性

已知有一个XML文件(book.xml)如下:  
  <?xml   version="1.0"   encoding="utf-8"?>  
  <bookstore>  
      <book   name="flashLite手机开发"   ISBN="2-3631-4">  
          <title>程序设计</title>  
          <author>王耐</author>  
          <price>58</price>  
      </book>  
  </bookstore>

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;//------------加入命名空间
namespace Xml练习
{
    class Program
    {
        static void Main(string[] args)
        {
            try//-------------------养成好的习惯 方便调试
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("book.xml");
                //该文件在debug路径下 是相对路径
                XmlNode root = xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>  
                XmlElement xe1 = xmlDoc.CreateElement("book");//创建一个<book>节点  
                xe1.SetAttribute("name", "王耐");//设置该节点genre属性  
                xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性  

                XmlElement xesub1 = xmlDoc.CreateElement("title");
                xesub1.InnerText = "CS从入门到精通";//设置文本节点  
                xe1.AppendChild(xesub1);//添加到<book>节点中  
                XmlElement xesub2 = xmlDoc.CreateElement("author");
                xesub2.InnerText = "Naiking";
                xe1.AppendChild(xesub2);
                XmlElement xesub3 = xmlDoc.CreateElement("price");
                xesub3.InnerText = "58.3";
                xe1.AppendChild(xesub3);

                root.AppendChild(xe1);//添加到<bookstore>节点中  
                xmlDoc.Save("book.xml");
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
                Console.Read();
            }
        }
    }
}


 

posted on 2009-01-11 22:27  醒着/☆☆  阅读(403)  评论(0)    收藏  举报