在序列化期间显示所有属性和字段

时间:2013-06-06 07:41:20

标签: c# xml serialization nullable

我有这个XML文件:

<?xml version="1.0" encoding="us-ascii"?>
<body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <header><user>BOBBY</user></header>
    <in>
        <customer>0123456789</customer>
    </in>
    <out>
        <cmd>
            <productid></productid>
            <price></price>
            <date></date>
            <state></state>
            <type></type>
        </cmd>
        <cmd>
            <productid></productid>
            <price></price>
            <date></date>
            <state></state>
            <type></type>
        </cmd>
    </out>
    <state>
        <code></code>
        <desc></desc>
    </state>
</body>

使用该文件,我生成了这个CSS类:

    //------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :2.0.50727.5456
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DAL.XML.PDD.Test
{
    using System.Xml.Serialization;

    // 
    // This source code was auto-generated by xsd, Version=2.0.50727.3038.
    // 


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class body
    {

        private object[] itemsField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("enter", typeof(bodyEnter), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public bodyEnter enter = new bodyEnter();

        [System.Xml.Serialization.XmlElementAttribute("header", typeof(bodyHeader), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public bodyHeader header = new bodyHeader();

        [System.Xml.Serialization.XmlElementAttribute("result", typeof(bodyResult), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public bodyResult result = new bodyResult();

        [System.Xml.Serialization.XmlElementAttribute("state", typeof(bodyState), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public bodyState state = new bodyState();


        public object[] Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class bodyEnter
    {

        private string customerField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string customer
        {
            get
            {
                return this.customerField;
            }
            set
            {
                this.customerField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class bodyHeader
    {

        private string userField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string user
        {
            get
            {
                return this.userField;
            }
            set
            {
                this.userField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class bodyResult
    {

        private bodyResultCmd[] cmdField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("cmd", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public bodyResultCmd[] cmd
        {
            get
            {
                return this.cmdField;
            }
            set
            {
                this.cmdField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class bodyResultCmd
    {

        private string productidField;

        private string priceField;

        private string dateField;

        private string stateField;

        private string typeField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string productid
        {
            get
            {
                return this.productidField;
            }
            set
            {
                this.productidField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string price
        {
            get
            {
                return this.priceField;
            }
            set
            {
                this.priceField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string date
        {
            get
            {
                return this.dateField;
            }
            set
            {
                this.dateField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string state
        {
            get
            {
                return this.stateField;
            }
            set
            {
                this.stateField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class bodyState
    {

        private string codeField;

        private string descField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string code
        {
            get
            {
                return this.codeField;
            }
            set
            {
                this.codeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string desc
        {
            get
            {
                return this.descField;
            }
            set
            {
                this.descField = value;
            }
        }
    }
}

这很有效,但是当我将它序列化时,空的属性和元素是否存在:

<?xml version="1.0" encoding="utf-8"?>
<body xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <enter>
    <customer>0123456789</customer>
  </enter>
  <header>
    <user>Bobby</user>
  </header>
  <result />
  <state />
</body>

我在我的Cs类中添加了这段代码:

    [XmlElement(IsNullable=true)]
    [System.Xml.Serialization.XmlElementAttribute("enter", typeof(bodyEnter), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public bodyEnter enter = new bodyEnter();

但我有这个错误:

    **InvalidOperationException**

感谢的。

1 个答案:

答案 0 :(得分:1)

以下代码将:

  1. 从字符串中解析XML
  2. 将XML反序列化为.Net对象,
  3. 将客户名称输出到控制台(仅显示我们已从XML中读取值),
  4. 将.NET对象序列化回XML,
  5. 将序列化的XML输出到控制台。或者,您可以取消注释TextWriter行并使用文本编写器代替Console.Out,将XML写入名为“Test.xml”的文件。
  6. 即使不包含IsNullable属性,仍会显示空标记。

    此外,您的第一个XML样本与您序列化的样本之间存在差异 - 第一个“in”和“out”在第二个变为“enter”和“result”。我保留了第一个元素名称,但随时可以在XML和代码中更改它们以匹配。

    祝你好运!

    <强>代码

    using System;
    using System.CodeDom.Compiler;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    using System.Xml.Linq;
    using System.IO;
    
    namespace DAL.XML.PDD.Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                string sampleXML = 
                @"<?xml version='1.0' encoding='us-ascii'?>
                <body xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
                    <header>
                        <user>BOBBY</user>
                    </header>
                    <in>
                        <customer>0123456789</customer>
                    </in>
                    <out>
                        <cmd>
                            <productid></productid>
                            <price></price>
                            <date></date>
                            <state></state>
                            <type></type>
                        </cmd>
                        <cmd>
                            <productid></productid>
                            <price></price>
                            <date></date>
                            <state></state>
                            <type></type>
                        </cmd>
                    </out>
                    <state>
                        <code></code>
                        <desc></desc>
                    </state>
                </body>";
    
                XDocument doc = XDocument.Parse(sampleXML);
    
                // Create our serializer of type Body, so that we can fill out members
                XmlSerializer serializer = new XmlSerializer(typeof(Body));
    
                // Deserialize the parsed XML into .Net objects
                Body body = (Body)serializer.Deserialize(doc.CreateReader());
    
                // Example that we have parsed correctly - output BOBBY
                Console.WriteLine(body.Header.User);
    
                // Use this to write the xml to a file 
                //TextWriter textWriter = new StreamWriter("Test.xml");
    
                // Serialize this object (back into XML) and write it to the console with empty tags
                serializer.Serialize(Console.Out, body);
    
                Console.ReadLine();
            }
        }
    
        [XmlRoot("body")]
        public class Body
        {
            [XmlElement("header")]
            public Header Header { get; set; }
    
            [XmlElement("in")]
            public In In { get; set; }
    
            [XmlArray("out")]
            [XmlArrayItem("cmd")]
            public Cmd[] Cmd { get; set; }
    
            [XmlElement("state")]
            public State State { get; set; }
        }
    
        public class In
        {
            [XmlElement("customer")]
            public string Customer { get; set; }
        }
    
        public class Header
        {
            [XmlElement("user")]
            public string User { get; set; }
        }
    
        public class Cmd
        {
            [XmlElement("productid")]
            public string ProductId { get; set; }
    
            [XmlElement("price")]
            public string Price { get; set; }
    
            [XmlElement("date")]
            public string Date { get; set; }
    
            [XmlElement("state")]
            public string State { get; set; }
    
            [XmlElement("type")]
            public string Type { get; set; }
        }
    
        public class State
        {
            [XmlElement("code")]
            public string Code { get; set; }
    
            [XmlElement("desc")]
            public string Desc { get; set; }
        }   
    }