当前位置导航:炫浪网>>网络学院>>网页制作>>XML/WebService教程

用XTW与XTR访问创建和读取XML文件

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Text;
        using System.Windows.Forms;
        using System.Xml;
        namespace XMLSAXDemo
        {
            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();
                }
                private void btnWrite_Click(object sender, EventArgs e)
                {
                    string fileName = "Books.xml";
                    XmlTextWriter writer = new XmlTextWriter(fileName, null);
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 6;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Books");
                    writer.WriteStartElement("Book");
                    writer.WriteElementString("Title", "Window Form");
                    writer.WriteElementString("ISBN", "111111");
                    writer.WriteElementString("Author", "amandag");
                    writer.WriteStartElement("Price");
                    writer.WriteAttributeString("Unit", "¥");
                    writer.WriteValue("128.00");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteStartElement("Book");
                    writer.WriteElementString("Title", "ASP.NET");
                    writer.WriteElementString("ISBN", "222222");
                    writer.WriteElementString("Author", "moon");
                    writer.WriteStartElement("Price");
                    writer.WriteAttributeString("Unit", "___FCKpd___0quot;);
                    writer.WriteValue("111.00");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Close();
                }
                private void btnRead_Click(object sender, EventArgs e)
                {
                    string fileName = "Books.xml";
                    XmlTextReader reader = new XmlTextReader(fileName);
                    string str = string.Empty;
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            if (reader.LocalName.Equals("Title") || reader.LocalName.Equals("Author"))
                            {
                                str += reader.ReadString() + " ";
                            }
                        }
                    }
                    MessageBox.Show(str);
                }
            }
        }

相关内容
赞助商链接