Linq to xml not working

Aikencura
Aikencura used Ask the Experts™
on
Hi

Can somebody explain me why my code isn't working?



 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Diagnostics;

namespace TelSearchModule
{
    public partial class _Default : System.Web.UI.Page
    {

       


        protected void Page_Load(object sender, EventArgs e)
        {
            ///Start Test
            
            // Load XML doc
            XDocument rssFeed = XDocument.Load("http://tel.search.ch/examples/api-response.xml");
            // Define XML Namespace
            XNamespace Atom = "http://www.w3.org/2005/Atom";
            XNamespace OpenSearch = "http://a9.com/-/spec/opensearchrss/1.0/";
            XNamespace tel = "http://tel.search.ch/api/spec/result/1.0/";

            var entries = from entry in rssFeed.Descendants("entry")
                          select new
                          {
                              Title = entry.Element("title").Value,
                              FirstName = entry.Element("tel:FirstName").Value
                          };
}
}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2008

Commented:
If the elements are in a different namespace, then you need to include those in the XDocument query.

Example:

http://msdn.microsoft.com/en-us/library/cc165615.aspx


planetsDoc = XDocument.Load("../../Planets.xml");
stacky.DataContext = planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements();

Author

Commented:
I don't understand, can you explain in "noob" language please..with my code.
If you test your suggestion, you get:
{"The '{' character, hexadecimal value 0x7B, cannot be included in a name."}
Most Valuable Expert 2012
Top Expert 2008
Commented:
There are different ways to build the query:

   Without the XNamespace reference:

            var entries = from entry in rssFeed.Descendants("{http://www.w3.org/2005/Atom}entry")
                          select entry;

or

   With the XNamespace reference:

              var entries = from entry in rssFeed.Descendants(Atom + "entry")
                          select new
                          {
                              Title = (string)entry.Element(Atom + "title"),
                              FirstName = (string)entry.Element(tel + "firstname")
                          };

Also, XML is case sensitive, so you need "firstname" and not "FirstName".

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial