c#
  • xml
  • xml-deserialization
  • 2012-04-06 4 views 3 likes 
    3

    Я знаю, что это было задано раньше, но я проверил другие темы, и никто не помог мне. Я пытаюсь десериализации XML в объект, и я получаю сообщение об ошибке:XML Deserializing Ошибка «Элемент не ожидался»

    "<doPublish xmlns='http://usdoj.gov/leisp/lexs/publishdiscover/3.1'> 
        was not expected." 
    

    Мой XML выглядит следующим образом:

    <lexspd:doPublish xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://usdoj.gov/leisp/lexs/publishdiscover/3.1 ../xsd/lexs/publish-discover/3.1/publish-discover.xsd" 
        xmlns:lexspd="http://usdoj.gov/leisp/lexs/publishdiscover/3.1" 
        xmlns:lexs="http://usdoj.gov/leisp/lexs/3.1"> 
        <lexs:PublishMessageContainer> 
         <lexs:PublishMessage> 
          <lexs:PDMessageMetadata> 
          </lexs:PDMessageMetadata> 
         </lexs:PublishMessage> 
        </lexs:PublishMessageContainer> 
    </lexspd:doPublish> 
    

    код, я использую для десериализации с внешностью, как:

    XmlSerializer xs = new XmlSerializer(typeof(PublishMessageType)); 
    Encoding encode = new UTF8Encoding(); 
    
    PDWebService lexpdServiceProxy = new PDWebService(); 
    lexpdServiceProxy.Url = "http://59.60.72.12/"; 
    
    String pdMessageXml = File.ReadAllText(fileName); 
    
    DoPublishType doPublishType = new DoPublishType(); 
    MemoryStream publishMsgMemStream = new MemoryStream(encode.GetBytes(pdMessageXml)); 
    doPublishType.PublishMessageContainer = new PublishMessageType[1]; 
    doPublishType.PublishMessageContainer[0] = 
        (PublishMessageType)xs.Deserialize(publishMsgMemStream); 
    

    И объект Я пытаюсь десериализации тоже выглядит следующим образом: (сокращенный вариант)

    /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Web.Services.WebServiceBindingAttribute(Name = "PDWebServiceSoapBinding", Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1/ws")] 
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(SRMessageType))] 
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(AugmentationType))] 
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(PayloadObjectReferenceType))] 
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(ComplexObjectType))] 
    [System.Xml.Serialization.XmlIncludeAttribute(typeof(MetadataType))] 
    public partial class PDWebService : System.Web.Services.Protocols.SoapHttpClientProtocol 
    { 
    
        private System.Threading.SendOrPostCallback doPublishOperationCompleted; 
    
        /// <remarks/> 
        public PDWebService() 
        { 
         this.Url = "http://localhost:9080/PDWebService/services/PDWebServiceBean"; 
        } 
    
        /// <remarks/> 
        public event doPublishCompletedEventHandler doPublishCompleted; 
    
        /// <remarks/> 
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:#doPublish", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Bare)] 
        [return: System.Xml.Serialization.XmlElementAttribute("doPublishReponse", Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1/ws")] 
        public doPublishReponse doPublish([System.Xml.Serialization.XmlElementAttribute("doPublish", Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1")] DoPublishType doPublish1) 
        { 
         object[] results = this.Invoke("doPublish", new object[] { 
           doPublish1}); 
         return ((doPublishReponse)(results[0])); 
        } 
    
        /// <remarks/> 
        public System.IAsyncResult BegindoPublish(DoPublishType doPublish1, System.AsyncCallback callback, object asyncState) 
        { 
         return this.BeginInvoke("doPublish", new object[] { 
           doPublish1}, callback, asyncState); 
        } 
    
        /// <remarks/> 
        public doPublishReponse EnddoPublish(System.IAsyncResult asyncResult) 
        { 
         object[] results = this.EndInvoke(asyncResult); 
         return ((doPublishReponse)(results[0])); 
        } 
    
        /// <remarks/> 
        public void doPublishAsync(DoPublishType doPublish1) 
        { 
         this.doPublishAsync(doPublish1, null); 
        } 
    
        /// <remarks/> 
        public void doPublishAsync(DoPublishType doPublish1, object userState) 
        { 
         if ((this.doPublishOperationCompleted == null)) 
         { 
          this.doPublishOperationCompleted = new System.Threading.SendOrPostCallback(this.OndoPublishOperationCompleted); 
         } 
         this.InvokeAsync("doPublish", new object[] { 
           doPublish1}, this.doPublishOperationCompleted, userState); 
        } 
    
        private void OndoPublishOperationCompleted(object arg) 
        { 
         if ((this.doPublishCompleted != null)) 
         { 
          System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); 
          this.doPublishCompleted(this, new doPublishCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); 
         } 
        } 
    
        /// <remarks/> 
        public new void CancelAsync(object userState) 
        { 
         base.CancelAsync(userState); 
        } 
    } 
        /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1/ws")] 
    public partial class doPublishReponse 
    { 
    
        private string responseStausField; 
    
        private doPublishReponseErrorDetails errorDetailsField; 
    
        /// <remarks/> 
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] 
        public string responseStaus 
        { 
         get 
         { 
          return this.responseStausField; 
         } 
         set 
         { 
          this.responseStausField = value; 
         } 
        } 
    
        /// <remarks/> 
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] 
        public doPublishReponseErrorDetails errorDetails 
        { 
         get 
         { 
          return this.errorDetailsField; 
         } 
         set 
         { 
          this.errorDetailsField = value; 
         } 
        } 
    } 
    

    Я попытался добавить:

    [System.Xml.Serialization.XmlRoot("doPublish", Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1", IsNullable = true)] 
    

    К верхней части класса я пытаюсь десериализации тоже не повезло. Я также попытался изменить объект XmlSerializer на:

    XmlRootAttribute xRoot = new XmlRootAttribute(); 
    xRoot.ElementName = "doPublish"; 
    xRoot.Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1"; 
    xRoot.IsNullable = true; 
    XmlSerializer xs = new XmlSerializer(typeof(PublishMessageType), xRoot); 
    

    Это будет работать, но каждый тип десериализованное объекта будет возвращать нуль, даже если все они населены в XML-документе.

    Любая помощь была бы замечательной, спасибо!

    +0

    Не могли бы вы назвать название класса, который хотите (се) сериализовать? Это doPublishReponse? Если это так, я не вижу [System.Xml.Serialization.XmlInclude (typeof (doPublishReponse))] в любом месте вашего прокси-класса – jbl

    +0

    Имя класса - PDWebService. Я также буду иметь класс doPublishResponse. –

    ответ

    5

    Я поместил ваш xml в файл «test.xml», а затем запустил xsd test.xml. Это привело к «test.xsd» и «test_app1.xsd». Я добавил элементы схемы из test_app1.xsd в test.xsd, а затем запустил xsd.test.xsd/classes.

    В результате:

    /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://usdoj.gov/leisp/lexs/3.1")] 
    [System.Xml.Serialization.XmlRootAttribute(Namespace="http://usdoj.gov/leisp/lexs/3.1", IsNullable=false)] 
    public partial class PublishMessageContainer { 
    
        private PublishMessageContainerPublishMessage[] publishMessageField; 
    
        /// <remarks/> 
        [System.Xml.Serialization.XmlElementAttribute("PublishMessage")] 
        public PublishMessageContainerPublishMessage[] PublishMessage { 
         get { 
          return this.publishMessageField; 
         } 
         set { 
          this.publishMessageField = value; 
         } 
        } 
    } 
    
    /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://usdoj.gov/leisp/lexs/3.1")] 
    public partial class PublishMessageContainerPublishMessage { 
    
        private string pDMessageMetadataField; 
    
        /// <remarks/> 
        public string PDMessageMetadata { 
         get { 
          return this.pDMessageMetadataField; 
         } 
         set { 
          this.pDMessageMetadataField = value; 
         } 
        } 
    } 
    
    /// <remarks/> 
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
    [System.SerializableAttribute()] 
    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    [System.ComponentModel.DesignerCategoryAttribute("code")] 
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://usdoj.gov/leisp/lexs/3.1")] 
    [System.Xml.Serialization.XmlRootAttribute(Namespace="http://usdoj.gov/leisp/lexs/3.1", IsNullable=false)] 
    public partial class doPublish { 
    
        private PublishMessageContainer[] itemsField; 
    
        /// <remarks/> 
        [System.Xml.Serialization.XmlElementAttribute("PublishMessageContainer")] 
        public PublishMessageContainer[] Items { 
         get { 
          return this.itemsField; 
         } 
         set { 
          this.itemsField = value; 
         } 
        } 
    } 
    

    Теперь работает следующий код в LINQPad, работает отлично.

    using(var stream = File.Open(@"..path here..\test.xml", FileMode.Open)) 
    { 
        XmlRootAttribute xRoot = new XmlRootAttribute(); 
        xRoot.ElementName = "doPublish"; 
        xRoot.Namespace = "http://usdoj.gov/leisp/lexs/publishdiscover/3.1"; 
        xRoot.IsNullable = true; 
    
        var serializer = new XmlSerializer(typeof(doPublish), xRoot); 
    
        var root = (doPublish)serializer.Deserialize(stream); 
    
        root.Dump(); 
    } 
    
    +0

    Спасибо, что это сработало, но после публикации объекта doPublish в веб-службе веб-служба возвращает «FAIL» и, как ни странно, скажет, что тип PublishMessageType имеет значение NULL. Даже если он заполняется, когда я просматриваю объект в режиме отладки Visual Studio. Как первоначально был настроен код, XmlSerializer десериализовал бы тип type PublishMessageType. Любые мысли о том, как заставить его десериализовать тип типа PublishMessageType? –

    +1

    Есть ли общедоступный URL-адрес, чтобы добавить ссылку на службу? – Phil

    0

    Возможно, пространство имен должно быть одинаковым в обоих случаях. Отказанный фрагмент XML отсутствует в конце «/ ws».

    +0

    Я попытался удалить ws из класса PDWebService и по-прежнему выдавал ту же ошибку. –

    Смежные вопросы