我已经构建了一个运行良好的Web服务,除了我试图删除xsi和xsd名称空间。
我看到很多链接显示我必须使用这样的自定义序列化器:
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
但我没有找到在我的代码中实现此方法的方法。这是我的代码:
[ServiceContract, XmlSerializerFormat]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyUser
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "getUserInfo?token={userId}", BodyStyle = WebMessageBodyStyle.Bare)]
public PersonnResponse ValidateToken(string userId)
{
var response = new PersonnResponse();
response.userId = userId;
response.firstName = myOtherServiceGetFirstName(userId);
response.lastName = myOtherServiceGetLastName(userId);
return response;
}
[DataContract(Name = "person", Namespace = "")]
public class PersonnResponse
{
[DataMember(Name = "userId", EmitDefaultValue = false)]
public string userId { get; set; }
[DataMember(Name = "firstName", EmitDefaultValue = false)]
public string firstName { get; set; }
[DataMember(Name = "lastName", EmitDefaultValue = false)]
public string lastName { get; set; }
}
答案 0 :(得分:1)
要获得您想要的内容,您应该实施IXmlSerializable:
[DataContract(Name = "person", Namespace = "")]
public class PersonnResponse:IXmlSerializable
{
...
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml (XmlReader reader)
{
var xd = XDocument.Load(reader);
firstName = xd.Descendants().First (x => x.Name.LocalName == "firstName" ).Value;
lastName = xd.Descendants().First (x => x.Name.LocalName == "lastName" ).Value;
userId = xd.Descendants().First (x => x.Name.LocalName == "userId" ).Value;
}
public void WriteXml(XmlWriter writer){
writer.WriteElementString("userId", userId);
writer.WriteElementString("firstName", firstName);
writer.WriteElementString("lastName", lastName);
}
}
public class Test
{
static void Main()
{
Test t = new Test();
t.Serialize();
}
private void Serialize()
{
// Create an instance of the class, and an
// instance of the XmlSerializer to serialize it.
var pers = new PersonnResponse(){ firstName="Call Me", lastName="Heisenberg", userId="Id"};
XmlSerializer ser = new XmlSerializer(typeof(PersonnResponse));
StringWriter tw = new StringWriter();
ser.Serialize(tw,pers);
Console.WriteLine(tw.ToString());
//Deserialize from XML string
var sw = new StringReader(tw.ToString());
var NewPerson = ser.Deserialize(sw);
}
}
你最终会得到这样的XML:
<?xml version="1.0" encoding="utf-16"?>
<PersonnResponse>
<userId>Id</userId>
<firstName>Call Me</firstName>
<lastName>Heisenberg</lastName>
</PersonnResponse>