使用xml声明反序列化WCF中的xml元素
本文关键字:xml 中的 元素 WCF 反序列化 声明 使用 | 更新日期: 2023-09-27 18:28:11
我有一个小WCF服务,它具有以下签名:
string ProcessMessage(XmlElement xmlSource);
当我收到一个没有xml声明的请求时,Web服务工作正常,但一旦添加了xml声明,我就会崩溃。
工作的请求
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:ProcessMessage>
<tem:xmlSource>
<clipped>elements here</clipped>
</tem:xmlSource>
</tem:ProcessMessage>
</soapenv:Body>
</soapenv:Envelope>
不起作用的请求
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:ProcessMessage>
<tem:xmlSource>
<?xml version="1.0" encoding="UTF-8"?>
<clipped>elements here</clipped>
</tem:xmlSource>
</tem:ProcessMessage>
</soapenv:Body>
</soapenv:Envelope>
崩溃:
<Message>No characters can appear before the XML declaration. Line 7, position 14.</Message>
<StackTrace>at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlUTF8TextReader.ReadDeclaration()
at System.Xml.XmlUTF8TextReader.Read()
at System.Xml.XmlBaseReader.MoveToContent()
at System.Xml.Serialization.XmlSerializationReader.ReadXmlNode(Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderINBUWProcessingService.Read1_ProcessMessage()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)</StackTrace>
<Type>System.Xml.XmlException</Type>
</InnerException>
<Message>There is an error in XML document (7, 14).</Message>
<StackTrace>at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)</StackTrace>
<Type>System.InvalidOperationException</Type>
我假设发生的情况是WCF服务将整个soap信封作为一个xml文档读取,然后当它遇到xml声明(参数xmlSource
)并将其解释为整个soap信封的xml文档时。这就是它崩溃的地方,它说xml声明必须是文档的第一部分。
有没有办法解决这个问题,或者在请求到达Web服务之前从请求中去掉xml声明?
发送给服务的XML无效。根据XML规范,XML声明只能出现在文档的序言中。格式良好的XML文档由prolog+根元素组成。元素节点中不允许使用XML声明。
您可能需要考虑将带有XML声明的文档作为字符串传递(例如,在<!'[CDATA'[
节中,或转义XML字符),这样您就可以在XML请求中接收XML"文档"。