C# 读写XML文件

phone.xml
<?xml version="1.0" encoding="utf-8" ?>
<PhoneBook>
 <phone id="001">
  <Name>加菲尔德</Name> 
  <Number>5555555</Number>
  <City>纽约</City>
  <DateOfBirth>26/10/1978</DateOfBirth>
 </phone>
 <phone id="002">
  <Name>迈克</Name>
  <Number>6666666</Number>
  <City>纽约</City>
  <DateOfBirth>12/02/1978</DateOfBirth>
 </phone>
</PhoneBook>


·使用Document读取及写入XML方法

 
private void xmlfun()
  {
   XmlDocument doc = new XmlDocument();
   doc.Load(Server.MapPath("phone.xml"));

   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(Server.MapPath("phone1.xml"));   //必须要存为不同的文件

  }




·使用XmlTextWriter写入XML方法

 
private void xmlwriter()
  {
   XmlTextWriter writer= new XmlTextWriter(Server.MapPath("phone4.xml"),null);
   writer.Formatting = Formatting.Indented;  //缩进格式
   writer.Indentation =4;

   writer.WriteStartDocument();

   writer.WriteStartElement("Person");

   writer.WriteStartAttribute("ID",null);
   writer.WriteString("004");
   writer.WriteEndAttribute();

   writer.WriteStartElement("Name");
   writer.WriteString("testWriterName");
   writer.WriteEndElement();

   writer.WriteStartElement("Number");
   writer.WriteString("88888");
   writer.WriteEndElement();

   writer.WriteStartElement("City");
   writer.WriteString("testWriterCity");
   writer.WriteEndElement();

   writer.Flush();
   writer.Close();

  }




·使用XmlTextReader读取XML方法

 
private void xmlread()
  {
      XmlTextReader reader = new XmlTextReader(Server.MapPath("phone.xml"));
      while(reader.Read())
      {
          if(reader.LocalName.Equals("Name") || reader.LocalName.Equals("Number"))
      {
      this.Label1.Text += reader.ReadString()+"\t";
  }




·作用 SqlCommand.ExecuteXmlReader()取得XML

SqlConnecting conn = new SqlConnection(CONNSTR);
SqlCommand cmd = new SqlCommand("select fname from employee for xml auto",conn);
conn.open();
XmlReader reader = cmd.ExecuteXmlReader();


################ 所取xml数据格式 #################

<employee fname="aria"/>
<employee fname="carlors"/>

你可能感兴趣的:(java,C++,c,xml,C#)