我在序列化中有以下类:
[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/