如何从 stations.xml 中拉出 URL,以在 ListBox 中播放

How to pull a URL from stations.xml, to play in the ListBox

如何从 stations.xml 中拉出 URL,以便在列表框中播放 (MouseDoubleClick)?

我的代码

XAML

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication6"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="220" Margin="20,30,0,0" VerticalAlignment="Top" Width="150" MouseDoubleClick="mylistbox"/>
    </Grid>
</Window>

这是我的 Xml 文件 stations.xml

<?xml version="1.0" encoding="utf-8"?>
<stations>
  <station url="http://onair.eltel.net:80/europaplus-128k" id="0">EuropaPlus2</station>
  <station url="http://online.radiorecord.ru:8101/rr_128" id="1">RRadio</station>
  <station url="http://radio.kazanturl-fm.ru:8000/mp3" id="2">Kazanturl</station>
  <station url="http://stream.kissfm.ua:8000/kiss" id="3">Kiss FM</station>
  </stations>

С#代码 enter link description here

您正在用不包含 "url" 属性的字符串填充您的列表框。一种选择是更改 LoadStations() 方法以将整个 XmlNode 添加到 ListBox 项。默认显示内文(站名)

public void LoadStations()
{
     string fileName = "data.xml";
     if (File.Exists(fileName))
     {
         XmlDocument xmlDoc = new XmlDocument();

         xmlDoc.Load(fileName);
         XmlNodeList stationNodes = xmlDoc.SelectNodes("//stations/station");
         foreach (XmlNode stationNode in stationNodes)
         {
              listBox.Items.Add(stationNode); // by default, the InnerText will be displayed                
         }

         xmlDoc.Save(fileName); 
    }
    else
    {
         MessageBox.Show(" ");
    }
}

然后,您可以像这样在 MouseDoubleClick 处理程序中提取 "url" 属性:

private void mylistbox(object sender, MouseButtonEventArgs e)
{            
   XmlNode selectedNode = listBox.SelectedItem as XmlNode;
   string url = selectedNode.Attributes["url"].Value;
   MessageBox.Show(url);
   Play(url);
}

此外,如果可能,您可能需要考虑使用 WPF 数据绑定从 XML 文件加载 ListBox 项。您可以通过将 ListBox 绑定到 XAML 中的 XML 文件来删除 LoadStations() 方法。像这样:

<Grid>
  <Grid.Resources>
    <XmlDataProvider x:Key="StationsXml" Source="stations.xml" />  
  </Grid.Resources>

  <ListBox HorizontalAlignment="Left" Height="220" Margin="20,30,0,0" 
       VerticalAlignment="Top" Width="150"            
       ItemsSource="{Binding Source={StaticResource StationsXml}, XPath=stations/station}"
       MouseDoubleClick="mylistbox"
          />
</Grid>