使用XmlWriter写入XML

时间:2011-05-04 16:13:47

标签: c# xml

我正在将数据写入XML文件,如下所示:

  protected void Page_Load(object sender, EventArgs e)
  {
      string xmlFile = Server.MapPath("savedata.xml");
      XmlTextWriter writer = new XmlTextWriter(xmlFile, null);

      writer.Formatting = Formatting.Indented;
      writer.Indentation = 3;

      writer.WriteStartDocument();

     //Write the root element
     writer.WriteStartElement("items");

     //Write sub-elements
     writer.WriteElementString("title", "First book title");
     writer.WriteElementString("title", "Second book title");
     writer.WriteElementString("title", "Third book title");

     // end the root element
     writer.WriteEndElement();

     //Write the XML to file and close the writer
     writer.Close();  
  }

但是,这会使用以下结构编写XML:

<items>
   <title>First book title</title>
   <title>Second book title</title>
<items>

但是我需要一个具有以下结构的XML文件:

<Symbols>
  <Symbol ExecutionSymbol="ATT" Name="AT&amp;T"></Symbol>
  <Symbol ExecutionSymbol="MSFT" Name="Microsoft"></Symbol>
</Symbols>

1 个答案:

答案 0 :(得分:1)

看看XmlWriter的其他方法。显然你想要写属性而不是元素。所以你必须使用WriteAttribute *方法而不是WriteElement *方法。