views:

22

answers:

1

I am trying to read in a simple XML file, however when I run the SQL it always returns Ennumeration Yeilded no results.

Not sure what I am going wrong.


XDocument xmlInfo = XDocument.Parse(xmlContent);
XNamespace ns = xmlInfo.Root.Name.Namespace;

 XNamespace ns = xmlBuilderInfo.Root.Name.Namespace;
 var Info = from XMLtagin xmlInfo.Descendants()
            where XMLtag.Name.LocalName == "XMLtag" 
            select new Information
                              {
                                  Name = XMLtag.Element("name").Value.ToString(),
                                  Region = XMLtag.Element("negion").Value.ToString()
                              };

            InfoList.SelectedIndex = -1;
            InfoList.ItemsSource = Info;

Any idea what I have done wrong???

Here is a sample of the XML file also

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<NameAndRegionDataSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
 <XMLTag>
  <Name>Content</Name>
  <Region>Peterborough</Region>
 </XMLTag>
 <XMLTag>
  <Name>Content</Name>
  <Region>Medicine Hat</Region>
 </XMLTag>
+1  A: 

You've got the casing wrong on "XMLtag" in the where clause should be "XMLTag".

Here is what I think this code should look like:-

XDocument xmlInfo = XDocument.Parse(xmlContent);

var Info = from XMLtag in xmlInfo.Root.Elements("XMLTag")
        select new Information
                          {
                              Name = (string)XMLtag.Element("Name"),
                              Region = (string)XMLtag.Element("Region")
                          };

Notes:-

  • XML is case-sensitive so you need to take care with element names
  • Avoid Descendents if you can it is slower and can lead to bugs
  • Your xml is in the no-name namespace so there is no need to muck about with namespaces
  • There is an implicit converted on XName from string, hence you don't need that where with LocalName.
  • There are explicit converted on XElement to various primitive types like String, by using a case to get the value of the element, missing elements result in null rather than an exception.
AnthonyWJones
The where clause was more of a typo than anything else in the posting.However I was making that much harder than it needed to be as it is much smoother now! Thank you so much!