How to make a C# web service accepts a custom object including unbound elements defined in XSD
I'm implementing a C# web service that is supposed to accept a custom message including unbounded number of elements.
Originally, the object is defined in a XSD file like below:
<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>
And, in a CS file implementing the web service, I prepared a struct for this:
public struct logevent
{
public ContextType context;
public struct ContextType
{
public string[] severity;
}
}
However, when I tried to access an element of the 'serverity' using a line,
String temp = logevent.context.severity.GetValue(0).ToString()
, the program throws a following error:
"Index was outside the bounds of the array."
When I changed the element from 'unbou开发者_开发技巧nded' to '1' in the XSD file and also modified 'public string[] severity;' to 'public string severity;', it works.
Can anyone help me to make the web service to accept a message including unbounded numbers of elements?
The code that corresponds to specified XSD (if serialized using XmlSerializer) is the following:
[XmlRoot("LogMessage"]
public class LogMessage
{
[XmlElement("avantlog")]
public LogEventType AvantLog {get; set;}
}
public class LogEventType
{
[XmlArray("context")]
[XmlArrayItem("severity")]
public string[] Severity {get; set;}
}
You may have to use attributes in order to control the deserialization of the incoming XML. By default, the supported XML structure for arrays follows the form:
<Elements>
<Element>X</Element>
<Element>Y</Element>
</Element>
However, your WSDL specifies unbounded "Element" terms and does not provide for a parent "Elements" block. My understanding is that in order to use unbounded terms, you need to specify attributes to control the deserialization, as unbounded terms are not the default in .NET WSDL generation and deserialization.
This article discusses how to control deserialization using attributes:
http://msdn.microsoft.com/en-us/library/2baksw0z.aspx
You can convert your XSD to a POCO object using "XSD.exe" and then use XmlSerializer. This will make it easy to interact with multiple external systems via XML. Might want to use SGen.exe as well to increase XmlSerializer
Performance. Hope this Helps
http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.71).aspx
http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm
精彩评论