使用XmlWriter写入XML

本文关键字:XML 写入 XmlWriter 使用 | 更新日期: 2023-09-27 17:54:57

我正在将数据写入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>

使用XmlWriter写入XML

看一下XmlWriter的其他方法。显然,您希望编写属性而不是元素。所以你必须使用WriteAttribute*方法而不是WriteElement*方法。