C# XML序列化不在XML中添加元素
我有一个从XSD生成的c类,我正在序列化它,我有一个场景,在特定条件下添加一些元素,这是我的类C# XML序列化不在XML中添加元素,c#,C#,我有一个从XSD生成的c类,我正在序列化它,我有一个场景,在特定条件下添加一些元素,这是我的类 [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribu
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class MyRequestClass
{
private string testNOField;
private string mOBNOField;
private int sTYPEField;
private System.DateTime fRMDATEField;
private System.DateTime tODATEField;
public string TESTNO
{
get
{
return this.testNOField;
}
set
{
this.testNOField = value;
}
}
public string MOBNO
{
get
{
return this.mOBNOField;
}
set
{
this.mOBNOField = value;
}
}
public int STYPE
{
get
{
return this.sTYPEField;
}
set
{
this.sTYPEField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
public System.DateTime FROMDATE
{
get
{
return this.fRMDATEField;
}
set
{
this.fRMDATEField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType = "date")]
public System.DateTime TODATE
{
get
{
return this.tODATEField;
}
set
{
this.tODATEField = value;
}
}
}
FromDate和ToDate属性将在特定条件下添加,问题是当我为这两个属性提供值时,它没有在XML中添加这些属性,也没有出现错误,尽管在本例中添加了其他元素。
这就是我连载的方式
string output = string.Empty;
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyRequestClass));
using (StringWriter sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
// sww.WriteLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
xsSubmit.Serialize(writer , env);
output = sww.ToString();
}
}
var doc = XDocument.Parse(output);
Enumerable<XElement> emptyElements;
emptyElements = from descendant in doc.Descendants()
where descendant.IsEmpty || string.IsNullOrWhiteSpace(descendant.Value)
select descendant;
emptyElements.Remove();
doc.Root.RemoveAttributes();
output = doc.ToString();
其次,我在两种不同的情况下序列化这个类,一种情况下MOBNO应该出现在XML中,另一种情况下它不应该出现,我应该如何实现这个特性?您可以动态添加/更改属性值,在这种情况下,隐藏元素将是XmlIgnore。代码如下:
if (yourCondition)
{
XmlAttributes myRequestClassPropertyAttributes = new XmlAttributes();
myRequestClassPropertyAttributes.XmlIgnore = true;
XmlAttributeOverrides myRequestClassAttributes = new XmlAttributeOverrides();
myRequestClassAttributes.Add(typeof(MyRequestClass), "MOBNO", myRequestClassPropertyAttributes);
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyRequestClass), myRequestClassAttributes);
using (StringWriter sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
// sww.WriteLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
xsSubmit.Serialize(writer, env);
output = sww.ToString();
}
}
}