Linq 查询不起作用

Linq-query doesn't work

我有一个 XML 文件,我试图在其中提取使用 Linq to XML 的信息。您会在下方找到我正在使用的 XML 文件的一部分。

<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>

我正在尝试使用以下代码提取名称:

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

但它一直返回 0。

我的查询有问题吗?

如有任何建议,我们将不胜感激。

您需要为元素指定 XML 默认命名空间:

XNamespace vm = "http://schemas.datacontract.org/2004/07/Pulse.Web.Api.External.ApiControllers.PreAlpha.ViewModels";
var Questions = myXML.Descendants(vm + "Event").Descendants(vm + "Name");  // ...