views:

931

answers:

3

Hello,

I'm using XmlTextWriter and its WriteElementString method, for example:

XmlTextWriter writer = new XmlTextWriter("filename.xml", null);

writer.WriteStartElement("User");
writer.WriteElementString("Username", inputUserName);
writer.WriteElementString("Email", inputEmail);
writer.WriteEndElement();

writer.Close();

The expected XML output is:

<User>
    <Username>value</Username>
    <Email>value</Email>
</User>

However, if for example inputEmail is empty, the result XML I get as as follows:

<User>
    <Username>value</Username>
    <Email/>
</User>

Whereas I would expect it to be:

<User>
    <Username>value</Username>
    <Email></Email>
</User>

What am I doing wrong? Is there a way to achieve my expected result in a simple way using XmlTextWriter?

+2  A: 

It doesn't fail <Tag/> is just a shortcut for <Tag></Tag>

RaYell
It is possible to force it to output <Tag></Tag>?
Roee Adler
I don't think so.
RaYell
+6  A: 

Your output is correct. An element with no content should be written as <tag/>.

You can force the use of the full tag by calling WriteFullEndElement()

writer.WriteStartElement("Email");
writer.WriteString(inputEmail);
writer.WriteFullEndElement();

That will output <Email></Email> when inputEmail is empty.

If you want to do that more than once, you could create an extension method:

public static void WriteFullElementString(this XmlTextWriter writer,
                                          string localName, 
                                          string value)
{
    writer.WriteStartElement(localName);
    writer.WriteString(value);
    writer.WriteFullEndElement();
}

Then your code would become:

writer.WriteStartElement("User");
writer.WriteFullElementString("Username", inputUserName);
writer.WriteFullElementString("Email", inputEmail);
writer.WriteEndElement();
Philippe Leybaert
+1  A: 

Your code should be:

using (XmlWriter writer = XmlWriter.Create("filename.xml"))
{
    writer.WriteStartElement("User");
    writer.WriteElementString("Username", inputUserName);
    writer.WriteElementString("Email", inputEmail);
    writer.WriteEndElement();
}

This avoids resource leaks in case of exceptions, and uses the proper way to create an XmlReader (since .NET 2.0).

John Saunders