DataContract反序列化XML

时间:2014-11-01 09:09:57

标签: c# xml wcf datacontractserializer xml-deserialization

我有这个XML:

<ResultData xmlns="http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities" 
            xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Information>Schedule added.</Information>
  <Success>true</Success>
</ResultData>

有没有办法只得到结果:

<ResultData>
  <Information>Sched added.</Information>
  <Success>true</Success>
</ResultData>

没有以下示例中的所有其他内容? 因为当我尝试获取下面显示的结果字符串的对象时,它不起作用。

Datacontract XML serialization

我尝试使用的代码是:

var serializer = new XmlSerializer(typeof(ResultData)); 
var rdr = new StringReader(xmlResultString);
var resultingMessage = (ResultData)serializer.Deserialize(rdr);

在最后一行显示错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

Additional information: There is an error in XML document (1, 2).

<ResultData xmlns='http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities'> was not expected.

ResultData:

[DataContract]
public class ResultData
{

    [DataMember] 
    public bool Success
    {
        get;
        set;
    }

    [DataMember] 
    public string Information
    {
        get;
        set;
    }

}

1 个答案:

答案 0 :(得分:1)

由于xml中的DataContract序列化命名空间,您将看到异常。理想情况下,您希望使用DataContractSerializer反序列化此值。

如果要使用XmlSerializer,则必须清理命名空间声明。以下将清理所有命名空间并允许您使用XmlSerializer。在foreach循环中,我们必须删除IsNamespaceDeclaration属性,然后将元素Name属性设置为LocalName。

string xmlResultString = @"<ResultData xmlns=""http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities"" 
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<Information>Schedule added.</Information>
<Success>true</Success>
</ResultData>";

var doc = XDocument.Parse(xmlResultString);

foreach (var element in doc.Descendants())
{
    element.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
    element.Name = element.Name.LocalName;
}
xmlResultString = doc.ToString();
var rdr = new StringReader(xmlResultString);
var serializer = new XmlSerializer(typeof(ResultData));
var resultingMessage = (ResultData)serializer.Deserialize(rdr);