开发者

How to stop XmlSerializer from adding newlines to blank elements

开发者 https://www.devze.com 2022-12-16 01:51 出处:网络
I am seria开发者_如何学Clizing an object like this: XmlSerializer serializer = new XmlSerializer(obj.GetType());

I am seria开发者_如何学Clizing 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.


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.


Found a simple route

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

hope this helps someone.

0

精彩评论

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

关注公众号