所以我能够在某个节点下选择所有结果,但我有以下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>
如果我想选择stopId,如果停止名称是Cysleys Farm(仅限请求),那么怎么办呢?
我有以下代码:
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;
编辑2
这些物品是否需要进入列表框?因为我需要字符串格式的值在URL上使用。
答案 0 :(得分: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();
答案 1 :(得分: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;
}
答案 2 :(得分: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);
}