2

I am getting 0 count result when i am converting XML to string array using XDcoument object to string array as per below

Stream dataStream = response.GetResponseStream();

XDocument doc = XDocument.Load((dataStream));

var services = from s in doc.Descendants("Location")
               select (string)s.Element("Name");

string[] locationArray = services.ToArray();

doc is as per below

<Locations xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Location>
    <Name>Anywhere US</Name>
  </Location>
  <Location>
    <Name>South Central US</Name>
  </Location>
  <Location>
    <Name>Anywhere Europe</Name>
  </Location>
  <Location>
    <Name>West Europe</Name>
  </Location>
  <Location>
    <Name>Anywhere Asia</Name>
  </Location>
  <Location>
    <Name>Southeast Asia</Name>
  </Location>
  <Location>
    <Name>East Asia</Name>
  </Location>
  <Location>
    <Name>North Central US</Name>
  </Location>
  <Location>
    <Name>North Europe</Name>
  </Location>
</Locations>

What should be wrong with the code to fetch array of location Name?

2 Answers 2

1

An interesting problem this was.

Because of your xmlns namespace, the element names all have that namespace. This works:

 var locations = from s in 
              doc.Descendants("{http://schemas.microsoft.com/windowsazure}Name")
                 select s.Value;

locations now contains all your locations

To make it more readable you could do this:

  var services = from s in doc.Descendants()
                 where s.Name.LocalName == "Location"
                 select s.Value;
Sign up to request clarification or add additional context in comments.

Comments

1

You have a namespace definition in you Locations element. So the name of the element is {http://schemas.microsoft.com/windowsazure}Location and not Location.

If you remove the namespace definition from the Locations element then will your query execute correctly and return a count of 9 Location elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.