个人代码库のXML操作演练

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsFormsApplication1
{
public partial class frm_MainForm : Form
{
//string Filename = null;


public frm_MainForm()
{
InitializeComponent();
}

private void btnNew_Click(object sender , EventArgs e)
{
SaveFileDialog sf
=new SaveFileDialog();
sf.Title
= "新建XML文件 ";
sf.Filter
= "XML文件(*.xml)|*.xml";
sf.ShowDialog(
this);
myMethod_XMLwriter(sf.FileName);

rtb_Editor.Text
= File.ReadAllText(sf.FileName);
}

private void myMethod_XMLwriter(string filename)
{
if ( filename != "" )
{
groupBox1.Enabled
= true;

//创建一个XML文档对象
XmlDocument xmlDoc = new XmlDocument();

//加入XML声明。
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0" , "UTF-8" , "yes"));

//加入XML注释。
xmlDoc.AppendChild(xmlDoc.CreateComment("注释"));

//加入空行。
xmlDoc.AppendChild(xmlDoc.CreateWhitespace(" \n"));

//创建一个根节点
//XmlElement xmlRoot = xmlDoc.CreateElement("root");
//创建一个根节点(带命名空间)
XmlElement xmlRoot = xmlDoc.CreateElement("YE" , "root" , "http://www.smartsoso.com");

//添加根节点
xmlDoc.AppendChild(xmlRoot);


//添加【CDATA数据】。
//xmlRoot.AppendChild(xmlDoc.CreateCDataSection("CDATA数据"));

//创建一个子节点
XmlElement bgcolor = xmlDoc.CreateElement("bgcolor");
bgcolor.SetAttribute (
"ID","yeye");
bgcolor.InnerText
= "red";//子节点的值
xmlRoot.AppendChild(bgcolor);//添加到根节点中

//保存到文件。
xmlDoc.Save(filename);





/*
//读
//创建一个XML对象
XmlDocument myxml = new XmlDocument();

// 读取已经有的xml
myxml.Load(Filename);

//声明一个节点存储根节点
XmlNode movie = myxml.DocumentElement;

//遍历根节点下的子节点
foreach ( XmlNode var in movie.ChildNodes )
{
//Console.WriteLine(var.Name);//获取根节点的名称
//Console.WriteLine(var.InnerText);//获取根节点的值!
rtb_Editor.Text += var.Name;
rtb_Editor.Text += var.InnerText;


}
*/


}
}
}
}

 

posted @ 2010-05-09 17:17  Asion Tang  阅读(367)  评论(0编辑  收藏  举报