现在我有一个serializable的类,定义如下:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.xxx.com")]
public class testType
{
private int AField;
private bool BField; /// <res/>
public decimal A
{
get
{
return this.AField;
}
set
{
this.AField = value;
}
}
/// <res/>
public bool B
{
get
{
return this.BField;
}
set
{
this.BField = value;
}
}
}
我用以下代码输出序列化对象后的XML文件
testType testObject = new testType();
testObject.AField = 0;
testObject.BField = true;
XmlSerializer xs = new XmlSerializer(typeof(testType));
TextWriter writer = new StreamWriter(targetPath);
xs.Serialize(writer, testObject);
writer.Close();
结果得到的XML文件中BField这个attribute输出是true。现在的问题是:
有没有方法让XML文档的BField这个attribute输出1,即<BField>1</BField>而不是<BField>true<BField>? 注意前提条件是不要改动testType类中BField的数据类型。因为这只是我造的一个例子,实际代码中有几十个类,很多bool类型的成员变量,如果都改变类型的话,工作量很大,也容易造成差错。我相信有各位高手有更好的解决方案,在此先谢谢了!
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.xxx.com")]
public class testType
{
private int AField;
private bool BField; /// <res/>
public decimal A
{
get
{
return this.AField;
}
set
{
this.AField = value;
}
}
/// <res/>
public bool B
{
get
{
return this.BField;
}
set
{
this.BField = value;
}
}
}
我用以下代码输出序列化对象后的XML文件
testType testObject = new testType();
testObject.AField = 0;
testObject.BField = true;
XmlSerializer xs = new XmlSerializer(typeof(testType));
TextWriter writer = new StreamWriter(targetPath);
xs.Serialize(writer, testObject);
writer.Close();
结果得到的XML文件中BField这个attribute输出是true。现在的问题是:
有没有方法让XML文档的BField这个attribute输出1,即<BField>1</BField>而不是<BField>true<BField>? 注意前提条件是不要改动testType类中BField的数据类型。因为这只是我造的一个例子,实际代码中有几十个类,很多bool类型的成员变量,如果都改变类型的话,工作量很大,也容易造成差错。我相信有各位高手有更好的解决方案,在此先谢谢了!
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.xxx.com")]
public class testType
{
private int AField;
private bool BField; /// <res/ >
public decimal A
{
get
{
return this.AField;
}
set
{
this.AField = value;
}
}
/// <res/ >
[XmlElement(DataType = typeof(byte))]
public bool B
{
get
{
return this.BField;
}
set
{
this.BField = value;
}
}
}
这个试试看。或者使用XmlAttributeOverrides
我没有自己试过,看了资料这个应该是是可以的。
按照你的方法, 加上[XmlElement(typeof(byte))]或者使用XmlAttributeOverrides 会抛出System.InvalidOperationException, Additional information: There was an error reflecting type ‘xxx.xxx.xxx’.To lextm
这个我知道没有意义,但是项目所用到XML schema标准规定就是0代表false,1代表true