现在我有一个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类型的成员变量,如果都改变类型的话,工作量很大,也容易造成差错。我相信有各位高手有更好的解决方案,在此先谢谢了!  

解决方案 »

  1.   

    XMLConvert类用来转换xml名字的,而那些toBoolean等函数最后转换到string还是true/false,没有解决问题。我现在的意思是要将bool值在XML文件中序列化成0/1,而不是true/false。
      

  2.   

    没用过,试诗,能不能先转换成Int 或 Byte
      

  3.   

    试试看能不能先将bool变换成Int或Byte,还有一种办法就是使用Xslt,把生成的Xml,转换一下,把里面的True/Flase转换为1/0后生成新的Xml文档
      

  4.   

    6楼说的XSLT我去试一下,还有更好的方法吗?
      

  5.   

    因为XML的schema很复杂,是自动生成的代码,有100多个类,所以要自己改动的话不现实
      

  6.   

        [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/ >
            [XmlElement(DataType = typeof(byte))]
            public bool B
            {
                get
                {
                    return this.BField;
                }
                set
                {
                    this.BField = value;
                }
            }
        } 
    这个试试看。或者使用XmlAttributeOverrides
    我没有自己试过,看了资料这个应该是是可以的。
      

  7.   

    感觉从true/false改成1/0没有什么实际意义,如果只是要减小XML文件大小,就更加没有必要,使用BinaryFormatter的效果会更好。
      

  8.   

    To lye2000000_super:
    按照你的方法, 加上[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