如何在属性之前将XmlNamespaces添加到XmlSerializer类型

时间:2016-03-04 14:17:14

标签: c# xsd attributes xmlserializer

我在C#中实现XSD。我使用XSD.EXE从XSD创建了c#类。 在XML中,有一个schemaVersion属性需要作为根级别的最后一个属性放置。 我将命名空间添加到xml,而Serialize为StreamWriter,命名空间在schemaVersion之后被序列化,我想在schemaVersion之前添加它,以便schemaVersion属性作为根级别的最后一个属性放置。

只有当schemaVersion属性是根级别的最后一个属性时,目标API才接受XML数据。

这是使用XSD.EXE生成的类代码

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.Test123.com")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.Test123.com", IsNullable = false)]
public partial class Request
{
    private decimal schemaVersionField;

    public Request()
    {                
            this.schemaVersionField = ((decimal)(4.0m));
    }
    [System.Xml.Serialization.XmlAttributeAttribute()]
       public decimal schemaVersion
       {
          get
            {
               return this.schemaVersionField;
            }
         set
           {
             this.schemaVersionField = value;
           }
       }
}

创建和发送webRequest的代码

public class WebRequestPost<T>
    {
        public void Post(T t)
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create("http://Test123.com/APIRequest");
            request.Method = "POST";        
            request.ContentType = "text/xml";
            var stream = request.GetRequestStream();
            StreamWriter writer = new StreamWriter(stream);

            var soapWriter = new XmlSerializer(typeof(T));            

           var ns = new XmlSerializerNamespaces();
           ns.Add("req", "http://www.Test123.com");

            soapWriter.Serialize(writer, t);            

            writer.Close();

            // Get the response.
            using (WebResponse response = request.GetResponse())
            {                     
                Stream dataStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }
}

输出我得到:

<?xml version="1.0"?>
<req:ShipmentRequest schemaVersion="4.0" xmlns:req="http://www.Test123.com">
</req:ShipmentRequest>

预期输出为:

<?xml version="1.0"?><req:ShipmentRequest xmlns:req="http://www.Test123.com" schemaVersion="4.0">
</req:ShipmentRequest>

任何人都知道如何在根级别添加特定属性作为最后一个属性? 任何帮助将不胜感激,提前谢谢。

谢谢, 苏希尔

0 个答案:

没有答案