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.
Source: stackoverflow.com
Related Query
- reading CDATA with linq to xml
- Reading an XML document with Linq
- C# Reading XML with LINQ
- Reading values from xml file with Linq
- Reading XML file with Linq
- Extracting inner value on CDATA with Linq to XML using a filter
- Reading XML with XDocument and LINQ Descendant Confusion
- I need to save the XML file using linq with xml code in C#
- Reading from a XML file with LINQ
- Reading an XML File With Linq
- C# Reading multiple elements with same name using LINQ to XML
- reading xml with linq (c#)
- twice reading xml file with linq
- Linq to xml with missing nodes in the source XML and null-coalescing operator won't work
- Reading XML using XDocument & Linq - check if element is NULL?
- How/Can I use linq to xml to query huge xml files with reasonable memory consumption?
- Update XML with C# using Linq
- LINQ to XML - accessing descendants with a prefix
- C# - Select XML Descendants with Linq
- Checking if a XML child element exists with Linq to XML
- Get excel cell value with Row and Column Position through open xml sdk linq query
- Parsing SOAP response with LINQ to XML - how to get nested nodes under parent?
- How to read XML file using System.IO.Stream with LINQ
- Parse XML with LINQ to get child elements
- Trying to parse XML tree with Linq to XML (C#)
- LINQ Source Code Available
- Better way to cleanly handle nested XML with LINQ
- Fragmented XML string parsing with Linq
- reading an XML string using LINQ
- Search XML doc with LINQ
More Query from same tag
- Joining a CSV file to query results
- How to write linq query to match SQL like select top 100 * from tab?
- Covert Linq to Expression Tree
- Easiest Way to get id or link and updated date from a RSS feed?
- Linq query that returns a summary of transaction
- How can a session variable hold a record from database?
- Internal access for entities in Entity Framework makes simple linq where query crash
- Using LINQ to map dynamically (or construct projections)
- How to group by multiple generic linq expressions
- How to use CopyToDataTable() method in LINQ successfully using below example only?
- ef core 5.0 How to Filtered Include
- linq groupby and max count
- Linq ToString() how do I convert?
- Duplicate elements when adding XElement to XDocument
- Is IEnumerable<T> Replace bad design?
- Does calling Select() or GroupBy() in Linq to entities trigger querying the database?
- How to effectively do dynamic query using LINQ against a Azure Cosmos Document DB SQL API?
- How to return only collection of certain entries from a complex type after query?
- Databind repeater using Linq with group by
- Asp.net, Linq Error: 'int' is a 'type' but is used like a 'variable'
- Find Any string contains List<>
- Get sum of two columns in one LINQ query without grouping
- How to retrieve a control with a certain property from a collection of Controls?
- Select Distinct Row from Data Table with Dynamic Columns
- Linq grouping .include("Table") returning null on Table
- Combine List of like DataTables
- Prepare Dynamic Lambda Expression with Checking parentproperty null control
- Trying to join two tables using LINQ, nothing is showing up
- Get total days (int) between DateTime.Now and a certain DateTime
- LINQ group-by and then display datetime for (dd mmm)