現在我將開始說這確實是一種分配。但是我已經接近完成了,直到我遇到了Linq to XML語法。LINQ to XML - 如何正確地使用XDocument
我有2個班級:跟蹤和CD現在作爲分配的一部分我創建一個CD,然後添加一些曲目。搜索了很多教程,完美地解釋瞭如何從xml到對象,我似乎無法得到這個工作(對象爲XML)。
我目前有:
//My list of cds
List<CD> cds = new List<CD>();
//Make a new CD and add some tracks to it
CD c1 = new CD("Awake","Dream Theater");
Track t1 = new Track("6:00", "Dream Theater", new TimeSpan(00, 05, 31));
Track t2 = new Track("Caught in a Web", "Dream Theater", new TimeSpan(00, 05, 28));
Track t3 = new Track("Innocence Faded", "Dream Theater", new TimeSpan(00, 05, 34));
c1.addTrack(t1);
c1.addTrack(t2);
c1.addTrack(t3);
cds.Add(c1);
//Make another cd and add it
CD c2 = new CD("Second cd","TestArtist");
Track t4 = new Track("TrackForSecond","TestArtist",new TimeSpan(00,13,37));
c2.addTrack(t4);
cds.add(c2);
現在,這是什麼讓我,我需要投入XML的對象。到XML部分是:
XDocument xmlOutput = new XDocument (
new XDeclaration("1.0","utf-8","yes"),
(from cl in cds orderby cl.getArtist()
select new XElement("cd", /*From new to the end of this is the error*/
(
from c in cds
select new XAttribute("artist",c.getArtist())
),
(
from c in cds
select new XAttribute("name", c.getTitle())
),
new XElement("tracks",
(
from t in c1.getTracks()
select new XElement("track",
new XElement("artist",t1.getArtist()),
new XElement("title",t1.getTitle()),
new XElement("length",t1.getLength())
)
)
)
)
)
);
Console.WriteLine(xmlOutput);
這很好(讓我得到我需要的結果!)僅1 CD。當我決定添加另一張cd時,它顯示:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.Linq.dll
Duplicate Attribute (cd)
這是指向XDocument。除了這個不工作,感覺非常愚蠢的(從C在CDS×2),但無論我嘗試,我似乎無法從恨我停止這種語法:
(
from c in cds
select new XAttribute("artist",c.getArtist()),
select new XAttribute("name", c.getTitle()) //No not happening!
),
會很樂意與任何幫助,您可以提供!
爲什麼不使用'XmlSerializer'類,然後將結果解析爲'XDocument'? – LukeHennerley
@LukeHennerley我還沒有聽說過,老師正在展示這些結構。 –
這看起來是一個很好的方式來問一個作業問題..你似乎錯過了什麼行異常發生雖然? – Sayse