• 原版对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;
    using System.Data.SqlClient;

    namespace WriteXML
    {
        public partial class WriteXMLForm : Form
        {
            string filename = string.Empty;
            public WriteXMLForm()
            {
                InitializeComponent();
            }

            private void btnXML_Click(object sender, EventArgs e)
            {
                XmlTextWriter writer = new XmlTextWriter("myMedia.xml",System.Text.Encoding.GetEncoding("GB2312"));
                //使用自动缩进便于阅读
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 4;
                writer.WriteStartDocument(true);
               
                //书写根元素
                writer.WriteStartElement("items");
                //开始一个元素。
                writer.WriteStartElement("item");
                //向先前创建的元素中添加一个属性
                writer.WriteAttributeString("rating", "R");
                //添加子元素
                writer.WriteElementString("title", "The Matrix");
                writer.WriteElementString("format", "DVD");
                //关闭item元素
                writer.WriteEndElement(); // 关闭元素
                //在节点间添加一些空格。
                writer.WriteWhitespace("\n");
                //使用原始字符串书写第二个元素
                writer.WriteRaw("  <item rating=\"R\">\n" +
                                "    <title>BloodWake</title>\n" +
                                "    <format>XBox</format>\n" +
                                "  </item>\n");
                //使用格式化的字符串书写第三个元素
                writer.WriteRaw("  <item rating=\"R\">\n" +
                                "     <title>Unreal Tournament 2003</title>\n" +
                                "     <format>CD</format>\n" +
                                "  </item>\n");
                // 关闭根元素。
                writer.WriteFullEndElement();
                // 写文档结束,调用WriteEndDocument方法
                writer.WriteEndDocument();


                //将XML写入文件并关闭writer
                writer.Flush();
                writer.Close();

            }

            private void btnWriteXml_Click(object sender, EventArgs e)
            {
                WriteXML();
            }

            private void WriteXML()
            {
                string connString = "Data Source=.;Initial Catalog=HouseDB;uid=sa;pwd=1;";
                string sql = "select * from Houses";
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                DataSet ds = new DataSet();
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                try
                {
                    conn.Open();
                    sda.Fill(ds);
                    Random rnd = new Random();
                    filename = DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Day;
                    filename += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + rnd.Next(100, 500).ToString();
                    XmlTextWriter xmlWriter = new XmlTextWriter(filename + ".xml",System.Text.Encoding.GetEncoding("UTF-8"));
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.WriteStartDocument(true);
                    xmlWriter.WriteStartElement("Hourse");
                    int i = 0;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        xmlWriter.WriteStartElement("房间" + (i+1).ToString());
                        xmlWriter.WriteElementString("HouseId", dr["HouseId"].ToString());
                        xmlWriter.WriteElementString("TypeName", dr["HouseTypeName"].ToString());
                        xmlWriter.WriteElementString("Area", dr["Area"].ToString());
                        xmlWriter.WriteElementString("Price", dr["Price"].ToString());
                        xmlWriter.WriteElementString("Address", dr["Address"].ToString());
                        xmlWriter.WriteElementString("CustomerId", dr["CustomerId"].ToString());
                        xmlWriter.WriteEndElement();
                        i++;
                    }
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();
                    xmlWriter.Flush();
                    xmlWriter.Close();
                    conn.Close();
                    conn.Dispose();
                }
                catch
                {
                    MessageBox.Show("数据库读取错误");
                    return;
                }
            }

            private void btnReadXML_Click(object sender, EventArgs e)
            {
                XmlDocument doc = new XmlDocument();
                XmlTextReader reader = new XmlTextReader(filename + ".xml");
                doc.Load(reader);
                XmlNode root = doc.DocumentElement;
                  //<房间1>
                  //  <HouseId>1</HouseId>
                  //  <TypeName>一室一厅</TypeName>
                  //  <Area>58</Area>
                  //  <Price>15000.0000</Price>
                  //  <Address>北京市海淀区成府路207号</Address>
                  //  <CustomerId>1</CustomerId>
                  //</房间1>
                XmlElement element = null;
                XmlElement houseElement = doc.CreateElement("房间7");
                root.AppendChild(houseElement);

                element = doc.CreateElement("HouseId");
                element.InnerText = "1";
                houseElement.AppendChild(element);

                element = doc.CreateElement("TypeName");
                element.InnerText = "四室三厅";
                houseElement.AppendChild(element);

                element = doc.CreateElement("Area");
                element.InnerText = "94";
                houseElement.AppendChild(element);

                element = doc.CreateElement("Price");
                element.InnerText = "4000.0000";
                houseElement.AppendChild(element);

                element = doc.CreateElement("Address");
                element.InnerText = "合肥工业大学产业楼三楼";
                houseElement.AppendChild(element);

                element = doc.CreateElement("CustomerId");
                element.InnerText = "1";
                houseElement.AppendChild(element);
                XmlTextWriter xmlWriter = new XmlTextWriter("MyHouse.xml",Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
               
                doc.Save(xmlWriter);

                foreach (XmlNode house in root.ChildNodes)
                {
                    TreeNode houseNode = this.tvHouses.Nodes.Add(house.Name);
                   foreach (XmlNode subNode in house.ChildNodes)
                   {
                       houseNode.Nodes.Add(subNode.InnerText);
                   }
                }
            }

            private void btnReader_Click(object sender, EventArgs e)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filename + ".xml");
               
                XmlNode xn = doc.SelectSingleNode("Hourse");
                XmlNodeList xnl = xn.ChildNodes;//获取Hourse节点的所有子节点
                foreach (XmlNode xnf in xnl) //遍历所有子节点
                {
                    XmlElement xe = (XmlElement)xnf; //将子节点类型转换为XmlElement类型
                    TreeNode node = this.tvHouses.Nodes.Add(xe.Name);

                    XmlNodeList xnf1 = xe.ChildNodes;
                    foreach (XmlNode xn2 in xnf1)
                    {
                       node.Nodes.Add(xn2.InnerText);//显示子节点文本
                    }
                }

            }
            private void xmlfun()
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("200942684257439.xml");
      //<phone id="003">
      //  <Name>testName</Name>
      //  <Number>119</Number>
      //  <City>cs</City>
      //  <DateOfBirth>12/02/1978</DateOfBirth>
      //</phone>
                XmlElement node = doc.CreateElement("phone");
                XmlAttribute atr = doc.CreateAttribute("id");
                atr.InnerText = "003";
                node.Attributes.Append(atr);

                XmlNode xnode = (XmlNode)doc.CreateElement("Name");
                xnode.InnerText = "testName";
                node.AppendChild(xnode);

                xnode = (XmlNode)doc.CreateElement("Number");
                xnode.InnerText = "119";
                node.AppendChild(xnode);
                xnode = (XmlNode)doc.CreateElement("City");
                xnode.InnerText = "cs";
                node.AppendChild(xnode);
                xnode = (XmlNode)doc.CreateElement("DateOfBirth");
                xnode.InnerText = "12/02/1978";
                node.AppendChild(xnode);
                doc.DocumentElement.InsertAfter(node, doc.DocumentElement.LastChild);

                doc.Save("phone1.xml");

            }


            private void btnXml3_Click(object sender, EventArgs e)
            {
                xmlfun();
            }
        }
    }

    myMedia.xml

    <?xml version="1.0" encoding="gb2312" standalone="yes"?>

    <items>

        <item rating="R">

            <title>The Matrix</title>

            <format>DVD</format>

        </item>
      <item rating="R">
        <title>BloodWake</title>
        <format>XBox</format>
      </item>
      <item rating="R">
         <title>Unreal Tournament 2003</title>
         <format>CD</format>
      </item>
    </items>

    Books.xml

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <!-- This file represents a fragment of a book store inventory database -->
    <bookstore>
      <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
          <first-name>Benjamin</first-name>
          <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
      </book>
      <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
          <first-name>Herman</first-name>
          <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
      </book>
      <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
          <first-name>Sidas</first-name>
          <last-name>Plato</last-name>
        </author>
        <price>9.99</price>
      </book>
    </bookstore>

  • 相关阅读:
    ipython是python的交互式shell工具
    [pip]安装和管理python第三方包
    django 文件上传 研究
    matplotlib01
    mysql数据导出为excel文件
    怎么查看mysql的数据库编码格式
    动态图片、图表
    django 生成复杂的 PDF 文件(数据较多时)
    链接sql数据库并输出csv文件
    django生成文件txt、pdf(在生成 PDF 文件之前,需要安装 ReportLab 库)
  • 原文地址:https://www.cnblogs.com/lds85930/p/1444774.html
Copyright © 2020-2023  润新知