【发布时间】:2017-01-31 13:11:27
【问题描述】:
我有以下 XML(精简版)文件:
<Service z:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<routes>
<Route z:Id="i4">
<timetables>
<Timetable z:Id="i8">
<timetableId>11061</timetableId>
</Timetable>
<Timetable z:Id="i8">
<timetableId>11062</timetableId>
</Timetable>
</timetables>
</Route>
</routes>
</Service>
我能够得到第一个 ID:11061,但我希望得到第二个,在真实文件中会有几个其他的。但我假设一旦我能得到两个,它就会得到超过 2 个。
XDocument doc = XDocument.Load("timetableTest.xml");
XNamespace ns = "http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary";
var routeNames = (from n in doc.Descendants(ns + "Service").Descendants(ns + "routes").Descendants(ns + "Route")//.Descendants(ns + "timetables")//.Descendants(ns + "Service")
select new RootContainer
{
Services = (from s in n.Elements(ns + "timetables")//.Elements(ns + "clients")
// where n.Elements(ns + "Service") != null
select new Services
{
ServiceName = s.Element(ns + "Timetable").Element(ns + "timetableId").Value,
//serviceIconUrl = "/Assets/Services/" + s.Element(ns + "serviceName").Value + ".png",
// ServiceId = s.Element(ns + "serviceId").Value
}).ToList()
}).Single();
listServices.ItemsSource = routeNames.Services;
为了获得多个时间表 ID,我需要更改什么?
更新:我如何做同样的事情,但有两条路线?刚刚重新查看了原始的 xml 提要。
<Service z:Id="i1" xmlns="http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<routes>
<Route z:Id="i4">
<timetables>
<Timetable z:Id="i8">
<timetableId>11061</timetableId>
</Timetable>
<Timetable z:Id="i8">
<timetableId>11062</timetableId>
</Timetable>
</timetables>
</Route>
<Route z:Id="i4">
<timetables>
<Timetable z:Id="i8">
<timetableId>11061</timetableId>
</Timetable>
<Timetable z:Id="i8">
<timetableId>11062</timetableId>
</Timetable>
</timetables>
</Route>
</routes>
</Service>
【问题讨论】:
-
您发现在您选择的末尾有一个看起来很可疑的
.Single()。?另外msdn.microsoft.com/en-us/library/… 看起来比这个嵌套的 LINQ 容易得多