Itunes给了我一个我不习惯使用的导出xml结构(参见xml代码):
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<dict>
<key>68768</key>
<dict>
<key>Track ID</key><integer>68768</integer>
<key>Name</key><string>ABBA Medley</string>
<key>Artist</key><string>Party All Stars</string>
<key>Disc Number</key><integer>1</integer>
<key>Track Number</key><integer>17</integer>
<key>Persistent ID</key><string>B121116C66BE0F4B</string>
</dict>
<key>68781</key>
<dict>
<key>Track ID</key><integer>68781</integer>
<key>Name</key><string>Afflitto</string>
<key>Artist</key><string>Fiocco</string>
<key>Disc Number</key><integer>1</integer>
<key>Track Number</key><integer>9</integer>
<key>Persistent ID</key><string>5D09837999591307</string>
</dict>
<key>68793</key>
<dict>
<key>Track ID</key><integer>68793</integer>
<key>Name</key><string>Agadou</string>
<key>Artist</key><string>Saradossa Band</string>
<key>Disc Number</key><integer>1</integer>
<key>Track Number</key><integer>4</integer>
<key>Persistent ID</key><string>4DFFF3C3498C02B4</string>
</dict>
</dict>
</dict>
</plist>
我的目标是在c#中使用LinqToXml实现以下数组:
17 ABBA Medley B121116C66BE0F4B
9 Afflitto 5D09837999591307
4 Agadou 4DFFF3C3498C02B4
这甚至可能吗?
我写了一些基本的c#代码,但闪电击中了我......
XDocument doc = XDocument.Load(iTunesXmlFile);
var linqtoxml = from node in doc.Descendants("dict") select node; // ooo Boy :(
foreach (var dict in linqtoxml)
{
// and lightning bolt again...
}
Ps:显而易见,我无法改变xml结构 Pps:我知道,这是一个清理iTunes XML版本,但基本概念是作为案例研究提出的。
答案 0 :(得分:0)
我能想到的最佳解决方案是:
List<Track> MyTrackList = new List<Track>();
public class Track
{
public int TrackNumber { get; set; }
public string Name { get; set; }
public string PersistentID { get; set; }
}
XDocument doc = XDocument.Load(@"thexmlfile.xml");
var linqtoxml = from element in doc.Descendants("plist").Descendants("dict").Descendants("dict").Descendants("dict")
select element;
foreach (var dict in linqtoxml)
{
try
{
string myTrackNumber = dict.Descendants("key").Where(key => key.Value == "Track Number").Select(x => x.NextNode).SingleOrDefault().ToString();
string myName = dict.Descendants("key").Where(key => key.Value == "Name").Select(x => x.NextNode).SingleOrDefault().ToString();
string myPersistentID = dict.Descendants("key").Where(key => key.Value == "Persistent ID").Select(x => x.NextNode).SingleOrDefault().ToString();
MyTrackList.Add(new Track
{
TrackNumber = myTrackNumber,
Name = myName,
PersistentID = myPersistentID
});
}
catch (Exception)
{
// Something wasn't set, so skip the node ...
}
}