开发者

Writing into XML with an XmlWriter

开发者 https://www.devze.com 2023-03-03 10:54 出处:网络
I\'m writing data into an XML file like the following: protected void Page_Load(object sender, EventArgs e)

I'm writing data into an XML file like the following:

  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 fi开发者_如何学Pythonle and close the writer
     writer.Close();  
  }

However this writes the XML with the following structure:

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

But I need an XML file with the following structure:

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


Have a look at other methods of XmlWriter. Obviously you want to write attributes instead of elements. So you have to use WriteAttribute* methods instead of WriteElement* methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消