c# - 带条件的 xml 序列化

标签 c# xml xml-serialization xmlserializer

我在序列化中有以下类:

[XmlRoot()]
public class XmlExample
{
private NodeA_Elem _nodea;
[XmlElemnt("NodeA")]
public NodeA_Elem NodeA
{
    get
    {
        return _nodea;
    }
    set
    {
        _nodea=value;
    }
}

private NodeB_Elem _nodeb;
[XmlElemnt("NodeB")]
public NodeB_Elem NodeB
{
    get
    {
        return _nodeb;
    }
    set
    {
        _nodeb=value;
    }
}

private NodeC_Elem _nodec;
[XmlElemnt("NodeC")]
public NodeC_Elem NodeC
{
    get
    {
        return _nodec;
    }
    set
    {
        _nodec=value;
    }
}
public class NodeA_Elem
{
    [XmlText()]
    public string value{get;set;}
}

public class NodeB_Elem
{
    [XmlText()]
    public string value{get;set;}
}

public class NodeC_Elem
{
    [XmlText()]
    public string value{get;set;}
}

如果任何类 NodaA、NodeB 或 NodeC 的值属性为 null 或为空,我将得到以下结果:

<XmlExample>
   <NodeA/>
   <NodeB/>
   <NodeC/>
</XmlExample>

如果我不设置 value 属性,我必须对这些节点执行的操作不会显示为空节点?

最佳答案

你可以使用 ShouldSerialize* 模式,像这样:-

public bool ShouldSerializeNodeA() {
    return NodeA != null;
}

引用这里:- Conditional xml serialization

更新:

使其不可为空:-

[XmlElement(IsNullable = false)]

编辑:

之前我提到过:-

public bool ShouldSerializeNodeA() {
    return NodeB != null;
}

我的错误,应该是这样的:-

public bool ShouldSerializeNodeA() {
    return NodeA != null;
}

关于c# - 带条件的 xml 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784343/

相关文章:

xml - 如何使用 XML::Twig 获取内容?

php - 如何将 SQL 查询结果转换为 XML?

c# - 与 .net 中的 Web 服务共享接口(interface)

c# - 接受 TCP 客户端异步

Android 开关小部件 : Setting android:track causes thumb and track to not show up

c# - XML 序列化导致重复节点

java - Simple Framework 中的自定义匹配器用于反序列化而不是序列化

c# - 将 Nullable<DateTime> 序列化为 XML

c# - 使用c#获取onload隐藏字段值

c# - 为什么当播放器对象被破坏时我的背景音乐停止播放?