0

我有这个 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**

谢谢。

4

1 回答 1

1

以下代码将:

  1. 从字符串解析您的 XML,
  2. 将 XML 反序列化为 .Net 对象,
  3. 将客户名称输出到控制台(只是为了表明我们已经从 XML 中读取了一个值),
  4. 将 .NET 对象序列化回 XML,然后
  5. 将序列化的 XML 输出到控制台。或者,您可以取消注释 TextWriter 行并使用文本编写器代替 Console.Out,将 XML 写入名为“Test.xml”的文件。

即使不包含 IsNullable 属性,仍会显示空标签。

此外,您的第一个 XML 样本与您正在序列化的样本之间存在差异——第一个样本的“输入”和“输出”在第二个样本中变成了“输入”和“结果”。我保留了第一个元素名称,但可以随意在 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; }
    }   
}
于 2013-06-09T05:32:04.527 回答