如何使C#Web服务接受自定义对象,包括在XSD中定义的未绑定元素

net*_*ear 6 c# web-services

我正在实现一个C#Web服务,该服务应该接受包含无限数量元素的自定义消息.

最初,该对象在XSD文件中定义,如下所示:

<xsd:element name="LogMessage">  
<xsd:complexType>  
<xsd:sequence>  
<xsd:element minOccurs="1" maxOccurs="1" name="avantlog" type="tns:LogEventType">  
</xsd:element>  
</xsd:sequence>  
</xsd:complexType>  
</xsd:element>  
<xsd:complexType name="LogEventType">  
<xsd:sequence>  
<xsd:element minOccurs="1" maxOccurs="1" name="context" type="tns:ContextType">  
</xsd:element>   
</xsd:sequence>  
</xsd:complexType>  
<xsd:complexType name="ContextType">  
<xsd:sequence>  
<xsd:element minOccurs="1" maxOccurs="unbounded" name="severity" type="xsd:string">  
</xsd:element>  
</xsd:sequence>  
</xsd:complexType>  
Run Code Online (Sandbox Code Playgroud)

并且,在实现Web服务的CS文件中,我为此准备了一个结构:

public struct logevent  
{  
public ContextType context;  
public struct ContextType  
{  
  public string[] severity;  
}  
}  
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用一行来访问'serverity'的元素时,

String temp = logevent.context.severity.GetValue(0).ToString()  
Run Code Online (Sandbox Code Playgroud)

,该程序抛出以下错误:

"Index was outside the bounds of the array."  
Run Code Online (Sandbox Code Playgroud)

当我在XSD文件中将元素从'unbounded'更改为'1'并且还修改了'public string [] severity;' 为'公共字符串严重性;',它的工作原理.

任何人都可以帮助我使Web服务接受包含无限数量元素的消息吗?

小智 0

您可能必须使用属性来控制传入 XML 的反序列化。默认情况下,支持的数组 XML 结构采用以下形式:

<Elements>
  <Element>X</Element>
  <Element>Y</Element>
</Element>
Run Code Online (Sandbox Code Playgroud)

但是,您的 WSDL 指定了无限制的“元素”术语,并且不提供父“元素”块。我的理解是,为了使用无界术语,您需要指定属性来控制反序列化,因为无界术语不是 .NET WSDL 生成和反序列化中的默认值。

本文讨论如何使用属性控制反序列化:

http://msdn.microsoft.com/en-us/library/2baksw0z.aspx