<代码>DataContractSerializer 既然由违约造成的,那么XML不能脱轨,但如果你使用一个包含<条码>的构造/代码>和<条码>的构造,可以照此办理。
另一种选择是使用<代码>XmlSerializer,你可以直接使用。
下面的法典显示了两种选择,也显示了使用XmlSerializer型号的网络方法。
public class StackOverflow_6399085
{
[XmlRoot(ElementName = "ServerName", Namespace = "http://schemas.microsoft.com/sqlazure/2010/12/")]
public class ServerName
{
[XmlText]
public string Name { get; set; }
public override string ToString()
{
return string.Format("ServerName[Name={0}]", this.Name);
}
}
const string XML = "<?xml version="1.0" encoding="utf-8"?><ServerName xmlns="http://schemas.microsoft.com/sqlazure/2010/12/">zpc0fbxur0</ServerName>";
static void RunWithXmlSerializer()
{
XmlSerializer xs = new XmlSerializer(typeof(ServerName));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
ServerName obj = (ServerName)xs.Deserialize(ms);
Console.WriteLine("Using XML serializer: {0}", obj);
}
static void RunWithDataContractSerializer()
{
DataContractSerializer dcs = new DataContractSerializer(typeof(string), "ServerName", "http://schemas.microsoft.com/sqlazure/2010/12/");
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
string name = (string)dcs.ReadObject(ms);
Console.WriteLine("Using DataContractSerializer (different name): {0}", name);
}
[ServiceContract(Namespace = "http://schemas.microsoft.com/sqlazure/2010/12/")]
public class MockSqlAzureRestService
{
[WebGet]
public Stream GetServerName()
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
return ms;
}
}
[ServiceContract(Namespace = "http://schemas.microsoft.com/sqlazure/2010/12/")]
public interface IServerNameClient
{
[WebGet(BodyStyle = WebMessageBodyStyle.Bare)]
[XmlSerializerFormat]
ServerName GetServerName();
}
static void RunWithWCFRestClient()
{
// Setting up the mock service
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(MockSqlAzureRestService), new Uri(baseAddress));
host.Open();
WebChannelFactory<IServerNameClient> factory = new WebChannelFactory<IServerNameClient>(new Uri(baseAddress));
IServerNameClient proxy = factory.CreateChannel();
var name = proxy.GetServerName();
Console.WriteLine("Using WCF REST client: {0}", name);
}
public static void Test()
{
RunWithXmlSerializer();
RunWithDataContractSerializer();
RunWithWCFRestClient();
}
}