I have a mail application. While sending to each recipient I am writing to an XML file named mail.xml. I use the following code:
Dim from As String = txtFrom.Text Dim txto As String = txtTo.Text Dim subj As String = txtSubject.Text Dim body As String = txtBody.Text Dim settings As New XmlWriterSettings() settings.Indent = True settings.NewLineOnAttributes = True Using writer As XmlWriter = XmlWriter.Create('C:\xmlmailfile.xml', settings) writer.WriteStartDocument() writer.WriteStartElement('EMail') writer.WriteStartElement('From') writer.WriteStartAttribute('From') writer.WriteValue(from) writer.WriteEndAttribute() writer.WriteStartElement('To') writer.WriteStartAttribute('To') writer.WriteValue(txto) writer.WriteEndAttribute() writer.WriteStartElement('Subject') writer.WriteStartAttribute('Subject') writer.WriteValue(subj) writer.WriteEndAttribute() writer.WriteStartElement('Body') writer.WriteStartAttribute('Body') writer.WriteValue(body) writer.WriteEndAttribute() writer.WriteEndElement() writer.WriteEndDocument() writer.Flush() End Using
And the output is:
<?xml version='1.0' encoding='utf-8' ?> <EMail> <From From='abc@xyz.com'> <To To='def@pqr.com'> <Subject Subject='Hi'> <Body Body='Hello' /> </Subject> </To> </From> </EMail>
Here I am not able to append to existing output. Only one ‘Email’ section is being output. I want to add an ‘Email’ section for each recipient. However, in the above code new sections replace previously written ones.
How can I accomplish this?
An XML document can only have a single root element. I suggest you have a root
Emailselement withEmailelements under it. Note that you still won’t be able to append new elements within the same file – you’d have to read the existing file and rewrite it. In theory you could just overwrite the last line (you always know how long it will be, so you could just seek to the right place) but it’s more robust to read the file into memory, append a newEmailelement, and then write out the whole document again.I also think it’s a bit strange to have the
Bodyelement within the subject element. I’d suggest a structure like this: