XML反序列化出现“Element was not expected”错误

4

我知道之前有人问过这个问题,但我查看了其他的帖子,没有一个能对我有所帮助。我正在尝试将XML反序列化为对象,但是出现了错误:

"<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);

这样做是可行的,但反序列化对象中的每个类型都会返回null,即使它们在xml文档中都已填充。如有帮助,感激不尽!

你能告诉我你想要(反)序列化的类的名称吗?是 doPublishReponse 吗? 如果是的话,我在你的代理类中没有看到 [System.Xml.Serialization.XmlInclude(typeof(doPublishReponse))] 这行代码。 - jbl
类的名称是PDWebService。我也会添加doPublishResponse类。 - Meyer Denney
2个回答

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();
}

谢谢,这个行了,但是当我把doPublish对象发布到Web服务后,Web服务返回“FAIL”,并且奇怪地说PublishMessageType为空,即使在Visual Studio调试模式下查看对象时它是有值的。最初设置代码的方式是XmlSerializer将反序列化为PublishMessageType类型。如何让它反序列化成PublishMessageType类型?你有什么想法吗? - Meyer Denney
1
有公共URL可以添加服务引用吗? - Phil

0
也许命名空间在两种情况下需要相同。被拒绝的 XML 片段末尾缺少“/ws”。

我尝试从PDWebService类中删除ws,但仍然出现相同的错误。 - Meyer Denney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接