-1

I have an XML-file where I'm trying to extract information of using Linq to XML. Below you'll find a piece of the XML-file I'm using.

<PulseViewModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Pulse.Web.Api.External.ApiControllers.PreAlpha.ViewModels">
    <Demographics />
    <Event>
        <Address i:nil="true" />
        <City i:nil="true" />
        <Country i:nil="true" />
        <Description i:nil="true" />
        <EndDateTimeUtc>2015-07-14T16:47:36</EndDateTimeUtc>
        <EstimatedParticipantsHigh>100</EstimatedParticipantsHigh>
        <EstimatedParticipantsLow>1</EstimatedParticipantsLow>
        <EventType i:nil="true" />
        <Location i:nil="true" />
        <Name>Test Event</Name>
        <StartDateTimeUtc>2015-07-14T13:47:36</StartDateTimeUtc>
        <State i:nil="true" />
        <TimeZoneDisplayName>Central Europe Daylight Time (UTC+120)</TimeZoneDisplayName>
        <TimeZoneId>Central Europe Standard Time</TimeZoneId>
        <TimeZoneOffset>120</TimeZoneOffset>
        <Zip i:nil="true" />
    </Event>
</PulseViewModel>

I'm trying to extract the name using the code below:

var Questions = myXML.Descendants("Event").Descendants("Name").Select(z => z.Value).FirstOrDefault();
MessageBox.Show(Questions.Count().ToString());

But it keeps returning 0.

Is there something wrong in my Query?

Any advice is appreciated.

GSerg
  • 76,472
  • 17
  • 159
  • 346
Cainnech
  • 439
  • 1
  • 5
  • 17
  • Try using Local Name : var Questions = myXML.Descendants("Event").Descendants().Where(x => x.Name.LocalName == "Name").Select(z => z.Value).FirstOrDefault(); – jdweng Jul 26 '15 at 21:17

1 Answers1

0

You need to specify the XML default namespace for your elements:

XNamespace vm = "http://schemas.datacontract.org/2004/07/Pulse.Web.Api.External.ApiControllers.PreAlpha.ViewModels";
var Questions = myXML.Descendants(vm + "Event").Descendants(vm + "Name");  // ...
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • Hi Douglas, That indeed did the trick. I've never had to do that before but I don't think the namespace was in my previous projects. So thank you! – Cainnech Jul 26 '15 at 21:18