I’m trying to write a windows phone 7 app which reads from an xml using xdocument but i’m having a few problems.
If I do this:
Dim xml As XDocument = XDocument.Load(e.Result)
System.Diagnostics.Debug.WriteLine(xml.ToString)
Or this:
System.Diagnostics.Debug.WriteLine(xml.Elements.Value.ToString)
then the xml data is output to the immidiate window as a string proving that the data exists but if i do this:
Dim products = From product In xml.Descendants("product") _
Select title = product.Element("title").Value
For Each product In products
System.Diagnostics.Debug.WriteLine("Title" & product.title)
Next
I get nothing for product.title and I also get nothing when I do stuff like this:
Dim count As Integer = xml.Descendants("count").Value
What am I doing wrong?
Thanks.
xml looks something like this:
<productslist>
<count>2</count>
<products>
<product>
<productId>1</productId>
<title>test item 1 </title>
<price>4.99</price>
<category>
<categoryId>1</categoryId>
<categoryName>cat 1</categoryName>
</category>
</product>
<product>
<productId>2</productId>
<title>test item 2</title>
<price>10.99</price>
<category>
<categoryId>2</categoryId>
<categoryName>cat 2</categoryName>
</category>
</product>
</productslist>
Your LINQ statement is not projecting into an anonymous type with a property of
Title. You’re getting anIEnumerable<string>back directly.Try this instead:
That said, the variable
productsis better namedtitles. If you want to project into an anonymous type you need to useWith New { .Prop1 = data, .Prop2 = other }. A dot must be prefixed to each property name. Here’s an example:For your example it doesn’t seem that an anonymous type is needed. If you have multiple properties to project into then it becomes worthwhile.
EDIT: in response to your comment, a namespace might be attached to your XML. If so, you would need to reference it to reference any element.
If your XML has a namespace it should have an
xmlnsspecified, such as:You would then have to modify your code to get the namespace and concatenate it with your elements as follows: