views:

52

answers:

2

I am serializing an object like this:

XmlSerializer serializer = new XmlSerializer(obj.GetType());            
using (StringWriter writer = new StringWriter())
{
    serializer.Serialize(writer, obj);
    return writer.ToString();
}

(having created the nodes like this)

XmlElement newchild = doc.CreateElement(nodename);
newchild.InnerText = data;
targetnode.AppendChild(newchild);

if data!="" all is well and serializer returns:

<mynode>TheData</mynode>

If data=="" the serializer returns:

<mynode>
</mynode>

Where did that blank line come from?

I've tried the obvious like only setting newchild.InnerText=data when data is nonblank.

+1  A: 

In XML both <mynode><\mynode> and <mynode>\n</mynode> are equivalent, so it should not matter, but you could modify the underlining XMLWriter to Serialize the output the way you want it.

Andrew Cox
Unfortunately they are not equivalent to the client app parsing my XML (over which I have no control). How would I modify the XMLWriter ?
Andiih
What version of .Net are you using?
Andrew Cox
3.5, but I think I've found a different route.
Andiih
A: 

Found a simple route

            if (data.Length == 0) newchild.IsEmpty = true;
            else newchild.InnerText = data;

hope this helps someone.

Andiih
If you are using an xml document why didn't you just use on of the Write methods on the document itself?
Andrew Cox
Good question. I may have to slap myself.
Andiih