The problem is the namespaces - for example, something like:
XNamespace ns = "http://api.cnet.com/rest/v1.0/ns";
XElement techProd = doc.Root.Element(ns + "TechProduct");
Product product = new Product {
Id = (int)techProd.Attribute("id"),
Name = techProd.Element(ns + "Name").Value,
Topic = techProd.Element(ns + "Topic").Value,
TopicId = (int)techProd.Element(ns + "Topic").Attribute("id"),
ImageUrl = techProd.Element(ns + "ImageURL").Value,
ImageWidth = (int)techProd.Element(ns + "ImageURL").Attribute("width"),
};
You might also prefer XmlSerializer
- something like:
XmlSerializer ser = new XmlSerializer(typeof(CnetResponse));
CnetResponse response = (CnetResponse)ser.Deserialize(new StringReader(xml));
TechProduct product = response.TechProduct;
With class definitions like:
[Serializable, XmlRoot("CNETResponse", Namespace = CnetResponse.Namespace)]
public class CnetResponse {
public const string Namespace = "http://api.cnet.com/rest/v1.0/ns";
public TechProduct TechProduct { get; set; }
}
[Serializable, XmlType(Namespace = CnetResponse.Namespace)]
public class TechProduct
{
[XmlAttribute("id")]
public int Id { get; set; }
public string Name {get;set;}
public Topic Topic { get; set; }
[XmlElement("ImageURL")]
public Image Image { get; set; }
}
[Serializable, XmlType(Namespace = CnetResponse.Namespace)]
public class Topic {
[XmlAttribute("id")]
public int Id { get; set; }
[XmlText]
public string Text {get;set;}
}
[Serializable, XmlType(Namespace = CnetResponse.Namespace)]
public class Image {
[XmlAttribute("width")]
public int Width { get; set; }
[XmlText]
public string Url {get;set;}
}
Or alternatively, just run the xml through xsd.exe
to get C# code to suit:
xsd foo.xml
xsd foo.xsd /classes