score:2

Accepted answer

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

score:1

Assuming that your Product class has the constructor used here, try this, where rawXml is the CNET response XML:

XElement cnetResponse = XElement.Parse(rawXml);

IEnumerable<NameQty> products =
    from e in cnetResponse.Descendants("TechProduct")
    select new Product(
        (string)e.Element("Name"),
        (int)e.Element("Topic").Attribute("id"),
        (string)e.Element("ImageURL")
    );

foreach(Product p in products)
{
    // do stuff
}

I have no access to a machine on which to test this, so I make no warranty.


Related Articles