2012-05-18 49 views
1

我有XML,看起來像這樣:數據綁定:在一個XML節點使用值來查找另一個

<showcases> 
<showcase id="260"> 
<artistID>2143</artistID> 
<venueID>29</venueID> 
<startdatetime>2012-09-12 17:30:00</startdatetime> 
<enddatetime>2012-09-12 18:00:00</enddatetime> 
</showcase> 
[etc] 
</showcases> 

而且在同一個XML文件中的這些:

<showcaseartists> 
<showcaseartist id="2129"> 
[other stuff about them] 
</showcaseartist> 
[etc] 
</showcaseartists> 

<venue id="19"> 
<name> ... </name> 
<address> ... </address> 
[etc] 
</venue> 

我怎麼去將這些數據放入列表中?

所以這樣的:

var showcasedata = from query in loadedData.Descendants("showcase") 
select new Showcase 
{ 
    StartDateTime = (DateTime)query.Element("startdatetime"), 
    ArtistName = ????, 
    Venue = ???? 
}; 
ShowcasesList.ItemsSource = showcasedata.ToList(); 

我想必須有一個辦法,但我無法找到它!

謝謝。

回答

0

快速和骯髒的方式:

var showcasedata = from query in loadedData.Descendants("showcase") 
select new Showcase 
{ 
    StartDateTime = (DateTime)query.Element("startdatetime"), 
    ArtistName = (string)loadedData.Elements("showcaseartist").First(e => (string)e.Attribute("id") == (string)query.Element("artistID")) 
}; 
ShowcasesList.ItemsSource = showcasedata.ToList(); 

應該對小XML文檔,但你會很快會遇到較大的文檔存在性能問題。對於那些使用字典緩存:

var artists = loadedData.Elements("showcaseartist").ToDictionary(e => (string)e.Attribute("id"), e => e); 

var showcasedata = from query in loadedData.Descendants("showcase") 
select new Showcase 
{ 
    StartDateTime = (DateTime)query.Element("startdatetime"), 
    ArtistName = (string)artists[(string)query.Attribute("id")].Element("artistID") 
}; 

它甚至會更好地把一個「藝術家」對象字典而不是XML節點。儘可能地將代碼調整到模型對象。

0

說你的類是什麼樣子

public class Showcase 
{ 
    public DateTime StartDateTime; 
    public string ArtistName; 
    public string Venue; 
} 

試試這個

var showcasedata = 
    from query1 in loadedData.Descendants("showcase") 
    select new Showcase() { 
     StartDateTime = (DateTime)query1.Element("startdatetime"), 
     ArtistName = (from query2 in loadedData.Descendants("showcaseartist") 
        where (int)query1.Element("artistID") == (int)query2.Attribute("id") 
        select (string)query2.Element("name")).First(), 
     Venue = (from query3 in loadedData.Descendants("venue") 
       where (int)query1.Element("venueID") == (int)query3.Attribute("id") 
       select (string)query3.Element("name")).First(), 
    }; 
相關問題