Reputation: 139
I'm trying to parse an xml file using LINQ, but as I understand the query returns null. (It's WP7) Here's the code:
var resultQuery = from q in XElement.Parse(result).Elements("Question")
select new Question
{
QuestionId = q.Attribute("id").Value,
Type = q.Element("Question").Attribute("type").Value,
Subject = q.Element("Subject").Value,
Content = q.Element("Content").Value,
Date = q.Element("Date").Value,
Timestamp = q.Element("Timestamp").Value,
Link = q.Element("Link").Value,
CategoryId = q.Element("Category").Attribute("id").Value,
UserId = q.Element("UserId").Value,
UserNick = q.Element("UserNick").Value,
UserPhotoURL = q.Element("UserPhotoURL").Value,
NumAnswers = q.Element("NumAnswers").Value,
NumComments = q.Element("NumComments").Value,
};
"result" is the xml string, just like this one. http://i48.tinypic.com/1ex5s.jpg (couldn't post properly formatted text so here's a pic : P )
Error: http://i48.tinypic.com/2uyk2ok.jpg
Sorry, if I haven't explained it properly and if this has already been asked (tried searching but didn't help).
Upvotes: 3
Views: 342
Reputation: 164341
You have run into an XML namespace problem. When you are just querying "Question", the string is translated into an XName
with the default namespace. There are no elements in the default namespace in your XML, only elements in the urn:yahoo:answers
namespace (see the top level element, where it says xmlns="urn:yahoo:answers"
).
You need to query the correct XML namespace, like this:
var ns = new XNameSpace("urn:yahoo:answers");
var resultQuery = from q in XElement.Parse(result).Elements(ns + "Question");
When picking out the individual properties, remember to add the namespace also.
XName
is a class that represents an XML name, which might have a namespace defined by XNameSpace
. These two classes has an implicit conversion operator implemented that allows you to implicitly convert from string
to XName
. This is the reason the calls work by just specifying a string
name, but only when the elements are in the default namespace.
The implicitness of this makes it very easy easier to work with XML namespaces, but when one does not know the mechanism behind, it gets confusing very quickly. The XName
class documentation has some excellent examples.
Upvotes: 3
Reputation: 1529
Two ways to fix it:
Upvotes: 0