我有一个处理简单 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>