1
這裏是XML文件的一部分,我讀:如何使用的XDocument讀取多個嵌入式元素
<?xml version="1.0"?>
<movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ThumbGen="1">
<hasrighttoleftdirection>false</hasrighttoleftdirection>
<title>A Nightmare on Elm Street</title>
<originaltitle>A Nightmare on Elm Street</originaltitle>
<year>1984</year>
<plot>Years after being burned alive by a mob of angry parents, child murderer Freddy Krueger returns to haunt the dreams -- and reality -- of local teenagers. As the town's teens begin dropping like flies, Nancy and her boyfriend, Glen, devise a plan to lure the monster out of the realm of nightmares and into the real world.</plot>
<tagline>A scream that wakes you up, might be your own...</tagline>
<metascore>78</metascore>
<trailer>http://www.youtube.com/watch?v=996</trailer>
<rating>8.6</rating>
<episodes />
<episodesnames />
<writers />
<gueststars />
<id>tt0087800</id>
<releasedate>11.09.1984</releasedate>
<actor>
<name>Robert Englund</name>
<name>Heather Langenkamp</name>
<name>Johnny Depp</name>
<name>Ronee Blakley</name>
<name>John Saxon</name>
<name>Amanda Wyss</name>
<name>Jsu Garcia</name>
<name>Charles Fleischer</name>
<name>Joseph Whipp</name>
<name>Lin Shaye</name>
<name>Joe Unger</name>
<name>Mimi Craven</name>
<name>David Andrews</name>
</actor>
<genre>
<name>Horror</name>
<name>Comedy</name>
</genre>
<director>
<name>Wes Craven</name>
</director>
<runtime>91</runtime>
<certification>R</certification>
<studio>
<name>New Line Cinema</name>
</studio>
<country>
<name>United States of America</name>
</country>
...
...
...
</movie>
感謝亨克Holterman,我能清理正在處理XML的代碼,我現在使用以下內容:
var doc = XDocument.Load(n); // takes care of all Open/Close issues
strTitle = doc.Root.Element("title") == null ? "" : doc.Root.Element("title").Value;
strYear = doc.Root.Element("year") == null ? "" : doc.Root.Element("year").Value;
strPlot = doc.Root.Element("plot") == null ? "" : doc.Root.Element("plot").Value;
strRating = doc.Root.Element("rating") == null ? "" : doc.Root.Element("rating").Value;
strMPAA = doc.Root.Element("mpaa") == null ? "" : doc.Root.Element("mpaa").Value;
strCertification = doc.Root.Element("certification") == null ? "" : doc.Root.Element("certification").Value;
現在最後一點,我該如何從流派元素使用此方法獲得流派?我無法搜索名稱元素,因爲它在各種其他元素中使用。我不知道我是否能一起工作:
doc.Root.Element("genre").ElementsAfterSelf("name");
並不在返回什麼明確的(我不太瞭解如何使用IEnumberables),或者將如何處理多個「名」。我認爲這可以用LINQ來完成,但我仍然試圖找出如何使用它。
非常感謝!
但這BOT資格作爲一個新的問題,您剛纔複製一切從最後一個。請編輯,以便它自己有意義。 –
如果我是你,我會寫一個單獨的函數,像'private string emptyOrValue(s){return s == null? string.Empty:s; }'。相同的代碼,但會清理你以上的混亂。你也可以用'(T)doc.Root.Element(「year」)等來提取T類型的值。 –