1

我有如下所示的 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();

我想一定有办法,但我找不到!

谢谢。

4

2 回答 2

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(),
    };
于 2012-05-18T05:21:49.567 回答
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 文档,但您很快就会遇到大型文档的性能问题。对于那些,使用 Dictionary 进行缓存:

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

将“Artist”对象放在 Dictionary 而不是 XML 节点中会更好。尽可能使代码适应您的模型对象。

于 2012-05-18T05:21:11.590 回答