以下代码有效,但我想完成相同的结果,即通过一个查询将元素“triptype”和“description”的不同值插入到列表中。任何帮助将不胜感激。
在此先感谢,马塞洛
class Program
{
static void Main(string[] args)
{
string xml = @"<Trips>
<Trip>
<triptype>vacation</triptype>
<description>Trip to Bahamas</description>
<id>89</id>
</Trip>
<Trip>
<triptype>vacation</triptype>
<description>Trip to California</description>
<id>75</id>
</Trip>
<Trip>
<triptype>business</triptype>
<description>Trip to Chicago</description>
<id>82</id>
</Trip>
</Trips>";
List<string> trips = new List<string>();
XDocument xdoc = XDocument.Parse(xml);
var tripTypes = (from t in xdoc.Descendants("Trip")
.Elements("triptype")
select t.Value).Distinct();
foreach (var tripType in tripTypes)
{
trips.Add(tripType);
}
var tripDescriptions = (from t in xdoc.Descendants("Trip")
.Elements("description")
select t.Value).Distinct();
foreach (var tripDescription in tripDescriptions)
{
trips.Add(tripDescription);
}
Console.ReadLine();
}
}