title: Cannot get values of some element & attributes when deserializing XML fragment into a C# class
body: <p>I am trying to deserialize XML to class.  I can get some values but not others.  </p>
  
  <p>Below is the result in which I can only get the Attribute in the root node.  The attributes and elements of other nodes do not get deserialized.</p>
  
  <p>result:</p>
  
  <pre><code>CategoryId  850113
  PersonId    null
  Name    null
  </code></pre>
  
  <p>Here is the code &amp; xml:</p>
  
  <pre><code>void Main()
  {
      var xml = GetXml();
      var x = Deserialize(typeof(GetCategoryResponse), xml);
      x.Dump();
  }
  
  private object Deserialize(Type typeToDeserialize, string xmlString)
  {
      var xdoc = XDocument.Parse(xmlString);
      var xRoot = new XmlRootAttribute { ElementName = xdoc.Root.Name.LocalName, IsNullable = false };
  
      byte[] bytes = Encoding.UTF8.GetBytes(xmlString);
      var mem = new MemoryStream(bytes);
      var ser = new XmlSerializer(typeToDeserialize, xRoot);
      return ser.Deserialize(mem);
  }
  
  public class GetCategoryResponse
  {
     [XmlAttribute("cat")]
     public string CategoryId { get;set; }
  
     [XmlAttribute("pid")]
     public string PersonId { get; set; }
  
     [XmlElementAttribute("pname")]
     public string Name { get; set; }
  }
  
  public string GetXml()
  {
      return @"&lt;response cat=""850113"" abID=""var.can.do"" uid=""8a561340-fab0-4389-a01d-e13e103b3204""&gt;
      &lt;test val=""cat""&gt;
          &lt;messsage&gt;There is a cat in the tree on my knee.&lt;/messsage&gt;
      &lt;/test&gt;
      &lt;person pid=""4433""&gt;
      &lt;pname&gt;Cherry Pop&lt;/pname&gt;
      &lt;/person&gt;
      &lt;/response&gt;";
  </code></pre>
  
  <p>}</p>
  
  <p>I tried using XSD but the class it generates is absolutely horrible - and doesn't work properly either.  While i can accomplish this manually I want the Deserialize method above to work generically with any class passed in (providing it has proper attributes for mapping to the xml fragment).</p>
  
  <p>Thanks a lot :-)</p>