【发布时间】:2009-05-18 20:51:19
【问题描述】:
我有一个 WCF 服务,它接受一个字符串作为其操作合同之一的参数。但是,此字符串中包含 xml 内容。
我需要将其转换为标记为DataContract 但不暴露于外界的类。
我需要使用DataContractSerializer,因为类成员的[DataMember] 属性设置为不同的名称。例如:Phone 属性的 DataMember Name 设置为 "Telephone",因此当我使用普通序列化程序反序列化 xmldocument 时,当反序列化程序查找不存在的 Phone 元素时出现错误。
如何使用DataContractSerializer 反序列化XmlDocument?一个限制是我无法将 xmldocument 保存到文件中。
编辑:找到一篇关于使用DataContractSerializer here.进行序列化和反序列化的优秀文章
我的客户代码:
string xmldata = "<Customer> +
System.Environment.NewLine+
"<Age>1</Age>"+
System.Environment.NewLine+
"<BirthDate>1900-01-01T01:01:01.0000000-05:00</BirthDate>" +
System.Environment.NewLine+
"<FistName>John</FistName>"+
System.Environment.NewLine +
"<LastName>Doe</LastName>" +
System.Environment.NewLine +
"</Customer>";
doc.LoadXml(xmldata);
Service1Client a = new Service1Client();
a.GetData(doc.OuterXml.ToString());
我的服务代码:
public string GetData(string per)
{
string xmldata = per;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmldata);
XmlDemo.Person a = Person.Create();
DataContractSerializer ser = new DataContractSerializer(a.GetType());
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlWriter);
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(stringWriter.ToString()));
stream.Position = 0;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
Person myContact = (Person)ser.ReadObject(reader, true);
return string.Empty;
}
我的数据合约:
[Serializable]
[DataContract(Name = "Customer")]
public class Person
{
private Person() {}
[DataMember(Name = "FistName")]
public string FName { get; set; }
[DataMember(Name = "LastName")]
public string LName { get; set; }
[DataMember(Name = "Age")]
public int Age { get; set; }
[DataMember(Name = "BirthDate")]
public DateTime DOB { get; set; }
public static Person Create()
{
return new Person();
}
}
我在 Person myContact = (Person)ser.ReadObject(reader, true); 处收到此错误;
第 1 行位置 11 出错。从命名空间“http://schemas.datacontract.org/2004/07/XmlDemo”中期待元素“客户”。遇到名称为“客户”、命名空间“”的“元素”。【问题讨论】:
-
能否请您重新表述问题并更具体一点。我不明白你想要什么