3

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).

4

2 回答 2

3

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 XNameclass documentation has some excellent examples.

于 2012-10-13T14:29:52.903 回答
0

Two ways to fix it:

  1. Add the root element was part since Elements only search one level - XElement.Parse(result).Root.Elements("Question")
  2. Use the Descendants method since that will search the entire xml tree.
于 2012-10-13T14:30:01.637 回答