xml操作

添加记录到ds保存到xml            

DataSet ds = new DataSet("myDs");
            //从XML中读取数据
            ds.ReadXml(Server.MapPath(@".dbdbGuest.xml"));
            //以下为添加记录
            DataRow dr = ds.Tables[0].NewRow();
            dr["Name"] = tbName.Text.Trim();
            dr["City"] = tbCity.Text.Trim();
            dr["Email"] = tbEmail.Text.Trim();
            dr["Message"] = tbComments.Text.Trim();
            dr["STime"] = DateTime.Now.ToString();
            ds.Tables[0].Rows.Add(dr);
            //写回XML
            ds.WriteXml(Server.MapPath("./db/dbGuest.xml"));
 用ds显示xml

DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath(@".dbdbGuest.xml"));
            dgShow.DataSource = ds.Tables[0].DefaultView;
            dgShow.DataBind();
 xml添加到ArrayList

<?xml version="1.0" encoding="utf-8" ?>
  <PEOPLE>
    <PERSON>张三</PERSON>
    <PERSON>李四</PERSON>
  </PEOPLE>
    XmlDocument doc = new XmlDocument();
            ArrayList NodeValues = new ArrayList();
            // 把people.xml文件读入内存,形成一个DOM结构
            doc.Load( Server.MapPath("people.xml") );
            XmlNode root = doc.DocumentElement;
            foreach( XmlNode personElement in root.ChildNodes )
                NodeValues.Add(personElement.FirstChild.Value);

            XMLNodeListBox.DataSource = NodeValues;
            XMLNodeListBox.DataBind();
创建xml文件

static void WriteXMLbyXmlWriter(XmlWriter writer, string symbol, double price, double change, long volume)
        ...{
            writer.WriteStartElement("Stock");
            writer.WriteAttributeString("Symbol", symbol);
            writer.WriteElementString("Price", XmlConvert.ToString(price));
            writer.WriteElementString("Change", XmlConvert.ToString(change));
            writer.WriteElementString("Volume", XmlConvert.ToString(volume));
            writer.WriteEndElement();
        }

        private void CreateXMLFileButton_Click(object sender, System.EventArgs e)
        ...{
            // 创建一个表示所要生成的XML文件路径的字符串。如果该路径指向NTFS分区,则需要相关的访问权限。
            string filename = XMLFilePathTextBox.Text;
            // 创建一个写入XML数据的文件流
            System.IO.FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            // 使用文件流对象创建一个XmlTextWriter对象
            XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);

            myXmlWriter.Formatting = Formatting.Indented;

            try
            ...{
                // 使用WriteXMLbyXmlWriter方法把数据写入XmlTextWriter对象中
                WriteXMLbyXmlWriter(myXmlWriter, "MSFT", 74.5, 5.5, 49020000);
                // 通过Close方法的调用,XmlTextWriter对象的数据最终写入XML文件
                myXmlWriter.Close();
                Page.Response.Write("生成XML文档成功!");
            }
            catch
            ...{
                Page.Response.Write("生成XML文档失败!请检查路径是否正确,以及是否有写入权限。");
            }
        }
 查找xml元素添加到下拉框

XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("./db/dbGuest.xml"));
            XmlNodeList elemList = doc.GetElementsByTagName("Name");
            ddlName.Items.Clear();
            for(int i=0;i<elemList.Count;i++)
             ddlName.Items.Add(elemList[i].InnerXml);
 重xml文件中取元素值

XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("./db/dbGuest.xml"));
            lbEmail.Text = doc.SelectSingleNode("//User[Name='"+ddlName.SelectedItem.Text+"']").ChildNodes.Item(2).InnerText;
        
 修改元素值

private void btnChange_Click(object sender, System.EventArgs e)
        ...{
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("./db/dbGuest.xml"));
            XmlNodeList nodeList=xmlDoc.SelectSingleNode("dbGuest").ChildNodes;//获取dbGuest节点的所有子节点
            foreach(XmlNode xn in nodeList)//遍历所有子节点
            ...{
                XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
           
                XmlNodeList node = xe.GetElementsByTagName("Name");
                if(node.Count>0)
                ...{

                    if(node[0].InnerText==ddlName.SelectedItem.Text)
                    ...{
                        XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
                        foreach(XmlNode xn1 in nls)//遍历
                        ...{
                            XmlElement xe2=(XmlElement)xn1;//转换类型
                            if(xe2.Name=="Email")//如果找到
                            ...{
                                xe2.InnerText=tbNewMail.Text;//则修改
                                break;//找到退出来就可以了
                            }
                        }
                        break;
                    }
                }
               
            }
            xmlDoc.Save(Server.MapPath("./db/dbGuest.xml"));
            Bind();
        }
 删除元素值

private void btnDelete_Click(object sender, System.EventArgs e)
        ...{
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("./db/dbGuest.xml"));
            XmlNodeList xnl=xmlDoc.SelectSingleNode("dbGuest").ChildNodes;
 
            foreach(XmlNode xn in xnl)
            ...{
                XmlElement xe=(XmlElement)xn;
                XmlNodeList node = xe.GetElementsByTagName("Name");
                if(node.Count>0)
                ...{

                    if(node[0].InnerText==ddlName.SelectedItem.Text)
                        xe.RemoveAll();//删除该节点的全部内容
                    break;
                }
            }
           
            xmlDoc.Save(Server.MapPath("./db/dbGuest.xml"));
            Bind();
        }

 添加xml元素

private void btnAdd_Click(object sender, System.EventArgs e)
        ...{
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath("./db/dbGuest.xml"));
            XmlNode root=xmlDoc.SelectSingleNode("dbGuest");//查找<dbGuest>
            XmlElement xe1=xmlDoc.CreateElement("User");//创建一个<User>节点
            XmlElement xesub1=xmlDoc.CreateElement("Name");
            xesub1.InnerText="Guset";//设置文本节点
            xe1.AppendChild(xesub1);//添加到<User>节点中
            XmlElement xesub2=xmlDoc.CreateElement("City");
            xesub2.InnerText="上海";
            xe1.AppendChild(xesub2);
            XmlElement xesub3=xmlDoc.CreateElement("Email");
            xesub3.InnerText="[email protected]";
            xe1.AppendChild(xesub3);
 
            root.AppendChild(xe1);//添加到<dbGuest>节点中
            xmlDoc.Save(Server.MapPath("./db/dbGuest.xml"));
            Bind();
        }<?xml version="1.0" standalone="yes"?>
<dbGuest>
  <User>
    <Name>Guset</Name>
    <City>上海</City>
    <Email>nmvvvv</Email>
  </User>
  <User>
    <Name>Guset</Name>
    <City>上海</City>
    <Email>[email protected]</Email>
  </User>
</dbGuest>
 上传图片到xml

private void btnUpload_Click(object sender, System.EventArgs e)
        ...{
            //得到用户要上传的文件名
            string strFilePathName = loFile.PostedFile.FileName;
            string strFileName = Path.GetFileName(strFilePathName);
            int FileLength = loFile.PostedFile.ContentLength;
            if(FileLength<=0)
                return;
            try
            ...{
                Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
                Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
                //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
                StreamObject.Read(FileByteArray,0,FileLength);
                string fileName = Server.MapPath("./WriteXml.xml");   //要打开的文件
           
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileName);
                XmlNode root=xmlDoc.SelectSingleNode("dbImage");//查找<dbGuest>
                XmlNodeList xnl=xmlDoc.SelectSingleNode("dbImage").ChildNodes;
                int nIndex = xnl.Count;
                //以下添加新结点
                XmlElement xe1=xmlDoc.CreateElement("Image");//创建一个<User>节点
                XmlElement xesub1=xmlDoc.CreateElement("ImageID");
                xesub1.InnerText=nIndex.ToString();//设置文本节点
                xe1.AppendChild(xesub1);//添加到<User>节点中
                XmlElement xesub2=xmlDoc.CreateElement("ImageContentType");
                xesub2.InnerText=loFile.PostedFile.ContentType;
                xe1.AppendChild(xesub2);
                XmlElement xesub3=xmlDoc.CreateElement("ImageSize");
                xesub3.InnerText=FileLength.ToString();
                xe1.AppendChild(xesub3);
                XmlElement xesub4=xmlDoc.CreateElement("ImageDescription");
                xesub4.InnerText=tbDescription.Text;
                xe1.AppendChild(xesub4);
                XmlElement xesub5=xmlDoc.CreateElement("ImageData");
                xesub5.InnerText= Convert.ToBase64String(FileByteArray);
                xe1.AppendChild(xesub5);


                root.AppendChild(xe1);//添加到<dbGuest>节点中
                xmlDoc.Save(fileName);
           
                Response.Redirect("ShowAllImg.aspx");
            }
            catch
            ...{
            }
        }
 取xml图片

int ImgID = Convert.ToInt32(Request.QueryString["ID"]); //ID为图片ID
            //建立数据库链接
            string fileName = Server.MapPath("./WriteXml.xml");   //要打开的文件
           
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList node =  xmlDoc.SelectSingleNode("//Image[ImageID='"+ImgID.ToString()+"']").ChildNodes;
            if(node!=null)
            ...{
                string strType = node.Item(1).InnerText;
                string strData =node.Item(4).InnerText;
                int nSize = int.Parse(node.Item(2).InnerText);

                Response.ContentType = strType;//设定输出文件类型
                //输出图象文件二进制数制
                Response.OutputStream.Write(Convert.FromBase64String(strData), 0, nSize);
                Response.End();
                //也可以保存为图像
                //            FileStream fs = new FileStream(@"C:aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
                //            fs.Write((Convert.FromBase64String(strData), 0,nSize);
                //            fs.Close();
            }
 校验xml

private void Page_Load(object sender, System.EventArgs e)
        ...{
            FileStream stream = new FileStream(Server.MapPath("people.xml"), FileMode.Open);
            //创建XmlValidatingReader类的对象
            XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null);
            //加载XML架构文档
            vr.Schemas.Add(null, Server.MapPath("people.xsd"));
            //说明验证的方式是根据XML架构
            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
            //对文档进行验证
            while(vr.Read());
            //显示验证过程完成
            Page.Response.Write("<b>Validation finished!<b>");
            //关闭打开的文件
            stream.Close();
        }

        private void ValidationHandler(object sender, ValidationEventArgs args)
        ...{
            //显示验证失败的消息
            Page.Response.Write("<b>Validation error: </b>" + args.Message + "<p>");
        }<?xml version="1.0"?>
<xs:schema id="PEOPLE" targetNamespace="http://tempuri.org/people.xsd" xmlns:mstns="http://tempuri.org/people.xsd" xmlns="http://tempuri.org/people.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:element name="PEOPLE" msdata:IsDataSet="true" msdata:Locale="zh-CN" msdata:EnforceConstraints="False">
    <xs:complexType>
      <xs:choice maxOccurs="unbounded">
        <xs:element name="PERSON" nillable="true">
          <xs:complexType>
            <xs:simpleContent msdata:ColumnName="PERSON_Text" msdata:Ordinal="0">
              <xs:extension base="xs:string">
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema><?xml version="1.0" encoding="utf-8"?>
<PEOPLE xmlns="http://tempuri.org/people.xsd">
    <PERSON>Tom</PERSON>
    <PERSON>Fred</PERSON>
</PEOPLE>

你可能感兴趣的:(xml,String,object,user,extension,dataset)