locked
LINQ to XML - Loading Entities from XML RRS feed

  • Question

  • I believe that I'm trying to do something incredibly simple. Yet, I can't figure out a clean way to do it. I have some XML that looks like this:

    <?xml version="1.0" encoding="ISO-8859-1" ?> 
    <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.somedomain.com/Response.xsd">
     <Results>
      <Result>
       <ID>1</ID>
       <Name>John Smith</Name>
       <Latitude>41.365736</Latitude>
       <Longitude>-82.511756</Longitude>
      </Result>
      <Result>
       <ID>2</ID>
       <Name>Bill Appleseed</Name>
       <Latitude>31.164736</Latitude>
       <Longitude>-72.611356</Longitude>
      </Result>
     </Results>
    </Response>
    

    I need to parse this XML and load it into some CLR objects. Currently, I'm doing the following:

    string response = GetXml();
    XDocument xml = XDocument.Parse(response);
    
    

    Beyond that, I'm stuck. No matter what I try, I get some error. Either a null pointer exception or something else. Can someone show me how you would tackle this problem?

    Thanks!

    Monday, December 27, 2010 10:04 PM

All replies

  • Anytime you get an error you should post enough code allowing others to reproduce the error, then we can suggest how to fix the problem.

    Here is some code sample that uses your posted sample XML and does not throw an error:

          XDocument doc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""ISO-8859-1"" ?> 
    <Response xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:noNamespaceSchemaLocation=""http://www.somedomain.com/Response.xsd"">
     <Results>
     <Result>
      <ID>1</ID>
      <Name>John Smith</Name>
      <Latitude>41.365736</Latitude>
      <Longitude>-82.511756</Longitude>
     </Result>
     <Result>
      <ID>2</ID>
      <Name>Bill Appleseed</Name>
      <Latitude>31.164736</Latitude>
      <Longitude>-72.611356</Longitude>
     </Result>
     </Results>
    </Response>");
          IEnumerable<Result> results = 
            from result in doc.Root.Element("Results").Elements("Result")
            select new Result() {
              Id = (int)result.Element("ID"),
              Name = (string)result.Element("Name"),
              Lat = (double)result.Element("Latitude"),
              Long = (double)result.Element("Longitude")
            };
          foreach (Result result in results)
          {
            Console.WriteLine("Id: {0}; Name: {1}; Latitude: {2}; Longitude: {3}", 
              result.Id, 
              result.Name, 
              result.Lat,
              result.Long);
          }
    
    
      public class Result
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Lat { get; set; }
        public double Long { get; set; }
      }
    

     


    MVP Data Platform Development My blog
    Tuesday, December 28, 2010 11:11 AM