0

所以我可以选择某个节点下的所有结果,但我有以下 XML

<ArrayOfStop>
 <Stop>
   <StopName>Rajdutt Restaurant</StopName>
   <route_stop />
   <route_stop_stop />
   <route_stop_timetable_stop />
   <stopId>6400</stopId>
 </Stop>
 <Stop>
   <StopName>Cysleys Farm (by request only)</StopName>
   <route_stop />
   <route_stop_stop />
   <route_stop_timetable_stop />
   <stopId>6401</stopId>
 </Stop>
<ArrayOfStop>

如果我想在停止名称是 Cysleys Farm 的情况下选择 stopId(仅通过请求),将如何处理?

我有以下代码:

XDocument loadedData = XDocument.Load("People.xml");

var data = from query in loadedData.Descendants("ArrayOfStop")
           select new Person
           { 
             StopName = (string)query.Element("StopName") 
           };

listBox.ItemsSource = data;

编辑:

var data = from query in loadedData.Descendants("ArrayOfStop") 
  where query.Element("StopName").Value == "Cysleys Farm (by request only)" 
  select query.Element("StopId").Value; 

select new Person
{
   FirstName = (string)query.Element("StopName"),
   //LastName = (string)query.Element("Long"),
   //Age = (int)query.Element("age")
};

listBox.ItemsSource = data;

Visual Studio 编辑器

编辑 2

这些项目是否需要进入列表框?因为我需要字符串格式的值才能在 url 上使用。

4

3 回答 3

1
        var doc =
            XDocument.Parse(
                "<ArrayOfStop><Stop><StopName>Rajdutt Restaurant</StopName><route_stop /><route_stop_stop /><route_stop_timetable_stop /><stopId>6400</stopId></Stop><Stop><StopName>Cysleys Farm (by request only)</StopName><route_stop /><route_stop_stop /><route_stop_timetable_stop /><stopId>6401</stopId></Stop></ArrayOfStop>");

        var list = (from item in doc.Descendants("Stop")
                    where (string) item.Element("StopName") == "Cysleys Farm (by request only)"
                    select (string)item.Element("stopId")).ToList();
于 2012-04-21T18:10:42.147 回答
0

这将为您提供具有匹配值的单个节点。如果您预计多个节点将具有匹配值并且只需要第一个,则使用FirstOrDefault而不是SingleOrDefault.

string search = "Cysleys Farm (by request only)";
var query = doc.Root.Elements()
            .SingleOrDefault( x => x.Element( "StopName" ).Value == search );

if (query != null)
{
    // if the query is not null, then this will be 
    // a single node with a root of <Stop>
    string id = query.Element( "stopId" ).Value;
}
于 2012-04-21T19:33:27.320 回答
0

另一种方法是:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("People.xml");

// Select the 'StopId' node whose StopName is 'Cysleys Farm (by request only)'
XmlNode stopIdNode = xmlDoc.SelectSingleNode("/ArrayOfStop/Stop[StopName='Cysleys Farm (by request only)']/stopId");

string stopId = stopIdNode.InnerText;

如果有多个节点具有相同的 StopName,那么您可以将它们存储在一个列表中:

List<string> stopIdList = new List<string>();

foreach (XmlNode stopIdNode 
         in xmlDoc.SelectNodes
         ("/ArrayOfStop/Stop[StopName='Cysleys Farm (by request only)']/stopId"))
{
    stopIdList.Add(stopIdNode.InnerText);
}
于 2013-09-24T18:17:37.450 回答