C#简单的Linq-to-XML查询只返回1个结果
本文关键字:返回 1个 结果 查询 简单 Linq-to-XML | 更新日期: 2023-09-27 18:28:03
我有一个处理简单xml的项目。但是我的LINQ查询不能正常工作。如果你能帮我的话。我有点困了。我有类似的项目正在顺利进行。下面是我处理C#的代码
void RecordsDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
XElement xml = XElement.Parse(e.Result);
String bandKey = bandID.Text;
IEnumerable<XElement> musicXml = xml.Elements("band");
Boolean foundRecords = false;
foreach (XElement band in musicXml)
{
if (band.Attribute("bandID").Value == bandKey)
{
ResultsListBox.ItemsSource = from song in band.Descendants("songs").Descendants("song")
select new Song
{
Name = song.Attribute("name").Value,
Sum = song.Attribute("sum").Value,
Number = song.Attribute("number").Value
};
foundRecords = true;
break;
}
else
{
foundRecords = false;
}
}
if (foundRecords)
{
if (ResultsListBox.Items.Count > 0)
{
MessageBox.Show("Music Band songs Record(s) Found!" + ResultsListBox.Items.Count);
}
}
else
{
MessageBox.Show("You do not have any Movie Session!");
ResultsListBox.ItemsSource = null;
}
}
}
和我的xaml代码
<ListBox Background="Black" Height="472" HorizontalAlignment="Left" Margin="0,148,0,0" Name="ResultsListBox" VerticalAlignment="Top" Width="480" SelectionChanged="ResultsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="120">
<StackPanel Width="350">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" FontSize="20" />
<TextBlock Text="{Binding Sum}" TextWrapping="Wrap" FontSize="16" />
<TextBlock Text="{Binding Number}" TextWrapping="Wrap" FontSize="16" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的班级代码
namespace MusicRateMobile
{
public class Song
{
public String Name { get; set; }
public String Sum { get; set; }
public String Number { get; set; }
}
}
和我的xml代码
<music>
<band bandID="1" name="Gorillaz">
<songs>
<song name="Feel Good" sum="4" number="1">
</song>
</songs>
</band>
<band bandID="2" name="Eminem">
<songs>
<song name="Mockingbird" sum="4" number="1"/>
<song name="Slimshaddy" sum="4" number="1"/>
</songs>
</band>
</music>
ResultsListBox.ItemsSource = from song in band.Descendants("song")
select new Song {
Name = song.Attribute("name").Value,
Sum = song.Attribute("sum").Value,
Number = song.Attribute("number").Value
};