1
我有一個這樣的XML:使用LINQ來元組的XML元素?
<?xml version="1.0" encoding="Windows-1252"?>
<!--XML Songs Database.-->
<Songs>
<Song><Name>My Song 1.mp3</Name><Year>2007</Year><Genre>Dance</Genre><Bitrate>320</Bitrate><Length>04:55</Length><Size>4,80</Size></Song>
<Song><Name>My Song 2.mp3</Name><Year>2009</Year><Genre>Electro</Genre><Bitrate>192</Bitrate><Length>06:44</Length><Size>8,43</Size></Song>
<Song><Name>My Song 3.mp3</Name><Year>2008</Year><Genre>UK Hardcore</Genre><Bitrate>128</Bitrate><Length>05:12</Length><Size>4,20</Size></Song>
</Songs>
我想存儲的元素放進一個數組或類似容易閱讀他們的東西。
我認爲元組的Lis將是一個很好的集合「容器」,如果不是,那麼我可以聽到建議。
我做了轉換,但沒有使用LINQ,我想簡化下面創建的元組使用LINQ的列表,而不是使用FOR +選擇情況下的代碼,所以我需要幫助重寫/改善這個代碼:
Dim Name As String = String.Empty
Dim Year As String = String.Empty
Dim Genre As String = String.Empty
Dim Bitrate As String = String.Empty
Dim Length As String = String.Empty
Dim Size As String = String.Empty
Dim SongsList As New List(Of Tuple(Of String, String, String, String, String, String))
Dim Elements As IEnumerable(Of XElement) = XDocument.Load(xmlfile).Descendants()
For Each Element As XElement In Elements
Select Case Element.Name
Case "Name"
Name = Element.Value
Case "Year"
Year = Element.Value
Case "Genre"
Genre = Element.Value
Case "Bitrate"
Bitrate = Element.Value
Case "Length"
Length = Element.Value
Case "Size"
Size = Element.Value
SongsList.Add(Tuple.Create(Name, Year, Genre, Bitrate, Length, Size))
End Select
Next
,並閱讀的歌曲我這樣做:
For Each song As Tuple(Of String, String, String, String, String, String) In SongsList
MsgBox(String.Format("Name:{1}{0}Year:{2}{0}Genre:{3}{0}Bitrate:{4}{0}Length:{5}{0}Size:{6}", _
Environment.NewLine, _
song.Item1, song.Item2, song.Item3, song.Item4, song.Item5, song.Item6))
' Output:
'
' Name:My Song 1.mp3
' Year:2007
' Genre:Dance
' Bitrate:320
' Length:04:55
' Size:4,80
Next
三江源,在這裏:'歌曲。 .Value'我可以使用某種Ignorecase作爲「'Name'」字符串? (在將來寫入這些字符串時,爲了防止出現語法錯誤,這是一個100%完美的代碼)。 –
ElektroStudios
@ElektroStudios否。因爲XML區分大小寫,所以會做錯誤的事情。因此,''標籤與''標籤不同,如果您的應用程序開始處理不同於標準的XML,它可能會非常麻煩。 –
sloth
這是一個完美的想法匿名類型!,是我第一次看到,你能說這是哪裏正確的聲明類型?:'對於每首歌作爲<匿名類型>在結果中# – ElektroStudios