XML反序列化问题

问题描述:

我想反序列化并读取一个简单的XML文件,下面的代码完成没有错误,但反序列化没有执行。XML反序列化问题

我的消息有一个节点,下面有三个元素。在Deserialize调用之后,我试图读取其中一个属性,它是空的。

public class Program 
    { 
     private string response = @"<?xml version=""1.0""?> 
<ApplicationException xmlns = ""http://schemas.datacontract.org/2004/07/System"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""> 
    <Name xmlns = """" i:type=""x:string"">System.ApplicationException</Name> 
    <Message xmlns = """" i:type=""x:string"">Error Message 12345</Message> 
    <DataPoints xmlns = """" i:nil=""true""/> 
</ApplicationException>"; 
     private XElement xElement; 
     private ExceptionClass theException; 

     public TestXML() 
     { 
      xElement = XElement.Parse(response); 
      var xmlSerializer = new XmlSerializer(typeof(ExceptionClass)); 
      using (var reader = xElement.CreateReader()) 
      { 
       theException = (ExceptionClass)xmlSerializer.Deserialize(reader); 
      } 
      Console.WriteLine(theException.Message); // nothing is showing up 
     } 
    } 

    [XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/System", 
      ElementName = "ApplicationException")] 
    public class ExceptionClass 
    { 
     public String Name { get; set; } 
     public String Message { get; set; } 
     public String DataPoints { get; set; } 
    } 
+0

捷克这一点:http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document –

问题是您将元素的XML名称空间设置为null,而根元素具有名称空间。试试这个:

public class ExceptionClass 
    { 
     [XmlElement(Namespace="")] 
     public String Name { get; set; } 
     [XmlElement(Namespace = "")] 
     public String Message { get; set; } 
     [XmlElement(Namespace = "")] 
     public String DataPoints { get; set; } 
    } 

这应该工作...

+0

这是问题。谢谢。 –