如何使用XAML检索XML属性

时间:2012-04-08 19:12:53

标签: c# wpf xml linq-to-xml

我有这个简单的XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Artists>
 <artist artistId="1">
<name>ManyBass</name>
<genre>Electronic</genre>
 <album>Fireblue</album>
 <player>
    <song path="Fireblue.mp3"/>
    <song path="Porthole.mp3"/>
</player>
 </artist>
</Artists>

我想检索所有歌曲路径,将其添加到ListBox中,如下所示:

XDocument loaded = XDocument.Load(path);
var q = from c in loaded.Descendants("player")
        select (string)c.Element("song path");
foreach (string track in q)
{
   myList.Items.Add(track);
}

但我的程序崩溃是因为跟踪字符串启动了SystemNullExceptionError。有人可以帮我正确检索属性:

  

歌曲路径

来自我的XML文件?谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

List<string> songs = (from c in loaded.Descendants("song")
                    select c.Attribute("path").Value).ToList();

并通过关闭Artist代码

来更正XML

答案 1 :(得分:3)

MVVM样式方法可以将ListBox直接绑定到XML文档,这样就不必在后面的代码中设置ListBox的内容。

XAML:

<Grid>
    <Grid.DataContext>
        <XmlDataProvider Source="Artists.xml" XPath="/Artists/artist"/>
    </Grid.DataContext>
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <TextBlock Text="{Binding XPath=./name}" DockPanel.Dock="Left"/>
                    <ListBox ItemsSource="{Binding XPath=./player/song}" DockPanel.Dock="Right">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding XPath=@path}"/>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </DockPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>      
</Grid>

答案 2 :(得分:2)

  • 您的XML错误,您尚未关闭<artist>代码
  • 您正在按名称"song path"访问元素,但您只有song元素,其中包含属性path

查询:

XDocument xdoc = XDocument.Load(path);

// type is IEnumerable<string>
var songs = xdoc.Descendants("song")                
                .Select(p => p.Attribute("path").Value);

修正了XML:

<?xml version="1.0" encoding="utf-8" ?>
<Artists>
<artist artistId="1">
   <name>ManyBass</name>
   <genre>Electronic</genre>
   <album>Fireblue</album>
   <player>
       <song path="Fireblue.mp3"/>
       <song path="Porthole.mp3"/>
   </player>
</artist>
</Artists>