C#XML序列化 [英] C# xml serialization

查看:134
本文介绍了C#XML序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我序列化对象到XML在C#中,我想序列化

I'm serializing an object to xml in c# and I would like to serialize

public String Marker { get; set; }

<Marker></Marker>

在字符串标记没有价值。

when string Marker has no value.

现在,我得到

<Marker />

标记==的String.Empty 无标记节点。 我怎样才能得到呢?

for Marker == string.Empty and no Marker node for null. How can I get this ?

推荐答案

您可以轻松燮preSS的&LT;标记&GT; 元素如果标记属性为null。只需添加一个 ShouldSerializeMarker()方法:

You can easily suppress the <Marker> element if the Marker property is null. Just add a ShouldSerializeMarker() method:

public bool ShouldSerializeMarker()
{
    return Marker != null;
}

这将是由的XmlSerializer 自动调用来决定是否要在输出中包含的元素。

It will be called automatically by XmlSerializer to decide whether or not to include the element in the output.

至于使用的扩展形式的&LT;标记&GT; 元素时字符串是空的,有没有简单的方法来做到这一点(你的可以大概写自己的的XmlWriter ,但是这将是一个痛苦)。但无论如何,它没有任何意义,因为&LT;标记/&GT; &LT;标记&GT;&LT; /标记&GT; 有相同的意思。

As for using the expanded form of the <Marker> element when the string is empty, there's no easy way to do it (you could probably write your own XmlWriter, but it would be a pain). But anyway it doesn't make sense, because <Marker /> and <Marker></Marker> have exactly the same meaning.

这篇关于C#XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆