Nizar B.
Nizar B.

Reputation: 3118

How to retrieve XML attributes with XAML

I have this simple XML file :

<?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>

I want to retrieve all song path to add it in a ListBox like this :

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);
}

But my program crash because the track string launch a SystemNullExceptionError. Can someone help me to retrieve properly the attribute :

song path

from my XML file ? Thanks for your help.

Upvotes: 0

Views: 1545

Answers (3)

Dan Busha
Dan Busha

Reputation: 3803

A MVVM styled approach would have you bind your ListBox directly to your XML document so that you don't have to set the contents of the ListBox in the back code.

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>

Upvotes: 3

sll
sll

Reputation: 62544

  • Your XML is wrong, you have not closed <artist> tag
  • You are accessing element by name "song path" but you have only song element with attribute path

Query:

XDocument xdoc = XDocument.Load(path);

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

Fixed 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>

Upvotes: 2

ionden
ionden

Reputation: 12786

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

And also correct the XML by closing the Artist tag

Upvotes: 3

Related Questions