Skip to main content
 首页 » 编程设计

c#之带条件的 xml 序列化

2024年08月06日33grandyang

我在序列化中有以下类:

[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; 
}