我希望将一个类序列化为XML。 它有效,但字符串属性" origen"总是被串行化为字符串,也是空的。 我希望序列化程序避免在它为空时将其包含在XML中
该类是FirmaElement,例如:
FirmaElement firma= new FirmaElement();
firma.Value="HITHERE";
firma.origen=String.Empty;
预期结果
string x= Serialize(FirmaElement);
x="<Firma>HITHERE</Firma>";
FirmaElement firma= new FIrmaElement();
firma.Value="HITHERE";
firma.origen="OK";
预期结果
string x= Serialize(FirmaElement);
x="<Firma origen='ok'>HITHERE</Firma>";
代码
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://gen/ces/headers/CesHeader")]
[System.Xml.Serialization.XmlRoot("Firma")]
public class FirmaElement
{
public FirmaElement() { }
string _origen = String.Empty;
string _value = String.Empty;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string origen
{
get { return _origen; }
set { _origen = value; }
}
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get { return _value; }
set { _value = value; }
}
public override string ToString()
{
return this.Value;
}
//IS THIS CORRECT? SHould i override something??
public string Serialize()
{
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
/* Setting XmlIgnore to false overrides the XmlIgnoreAttribute
applied to the Comment field. Thus it will be serialized.*/
attrs.XmlIgnore = String.IsNullOrEmpty(origen);
xOver.Add(typeof(string), "origen", attrs);
I DONT KNOW WHAT TO PUT HERE, IT'S CORRECT??
//XmlSerializer xSer = new XmlSerializer(typeof(XmlTypeAttribute), xOver);
}
}
答案 0 :(得分:1)
您可以使用名为ShouldSerialize{PropertyName}
的方法指定是否应该序列化特定属性。检查this answer。
答案 1 :(得分:0)
您应该将名为origenSpecified的属性添加到FirmaElement类中。
[XmlIgnore]
public bool origenSpecified
{
get
{
return !(string.IsNullOrEmpty(origen));
}
}