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).
You have run into an XML namespace problem. When you are just querying “Question”, the string is translated into an
XNamewith the default namespace. There are no elements in the default namespace in your XML, only elements in theurn:yahoo:answersnamespace (see the top level element, where it saysxmlns="urn:yahoo:answers").You need to query the correct XML namespace, like this:
When picking out the individual properties, remember to add the namespace also.
XNameis a class that represents an XML name, which might have a namespace defined byXNameSpace. These two classes has an implicit conversion operator implemented that allows you to implicitly convert fromstringtoXName. This is the reason the calls work by just specifying astringname, but only when the elements are in the default namespace.The implicitness of this makes it
very easyeasier to work with XML namespaces, but when one does not know the mechanism behind, it gets confusing very quickly. TheXNameclass documentation has some excellent examples.