DataContract反序列化XML

本文关键字:XML 反序列化 DataContract | 更新日期: 2023-09-27 18:28:37

我有这个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>

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

数据合约XML序列化

我尝试使用的代码是:

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.

结果数据:

[DataContract]
public class ResultData
{
    [DataMember] 
    public bool Success
    {
        get;
        set;
    }
    [DataMember] 
    public string Information
    {
        get;
        set;
    }
}

DataContract反序列化XML

由于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);