Search code examples
c#asp.netxmlxmlwriter

How to write an empty string into XML file with C#'s XmlWriter class?


I'm creating a program using C# (in ASP.NET environment) that makes an XML file. It uses XmlWriter class for writing, but there's one thing I'm not sure how to do.

Say, to write a string I do:

xmlWriter.WriteElementString("c1", "name");

which becomes:

< c1 >name< /c1 >

That is great, until I try to write an empty string:

xmlWriter.WriteElementString("c1", "");

which becomes:

< c1/ >

But how do you format it to be?

< c1 >< /c1 >


Solution

  • Both contructs (<c1/> and <c1></c1>) are identical from XML point of view, so it is very likely that compliant reader will not let you distinguish between them. If you need to have special "null" value consider using xsi:nil ( http://w3.org/TR/xmlschema-1/#xsi_nil ) which is designed for this.

    <c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>