2012-12-12 150 views
-5

我該如何解析這個XML數據的「問題」元素到名爲「問題」的對象中,並使用名爲「options」的字符串數組屬性?我知道有很多XML帖子的答案,但他們都混淆了我,我只是需要一個適合我的問題。在xml文件中總共有50個問題,我想提取每個問題元素,並將它的子元素和內容提取到問題對象中。我用C#在Visual Studio 2010中xml解析?如何?

<?xml version="1.0" encoding="utf-8" ?> 
<Questions> 
<Question id ="1"> 
<Content>Which of the following statements represents the view expressed by the writer in the first paragraph?</Content> 
<Options> 
    <A>Evil Thoughts will eventually ruin the evil man.</A> 
    <B>If we do not stop the pendulum of thoughts from swinging, our thoughts will soon become our enemies.</B> 
    <C>Too many evil thoughts leave fatal consequence.</C> 
    <D>It is possible to decide what controls our thoughts.</D> 
</Options> 
</Question> 
<Question id ="2"> 
<Content>From the argument in the second paragraph, it can be concluded that evil thoughts control the lives people who</Content> 
<Options> 
    <A>are helpless because they fly out of their minds</A> 
    <B>cherish idle and slothful ways</B> 
    <C>are thieves with evil instincts</C> 
    <D>treasure and ruminate on them.</D> 
</Options> 
</Question> 
<Question id ="3"> 
    <Content>The expression think of the devil and he will appear..., as used in this passage, suggests that</Content> 
<Options> 
    <A>like the devil, evil thoughts must not reign in our hearts</A> 
    <B>evil thoughts are fantasies which exist only in people's minds</B> 
    <C>uncontrolled evil thoughts may lead to evil deeds</C> 
    <D>the devil gives evil thoughts only to those who invite him in.</D> 
</Options> 
</Question> 
<Question id ="4"> 
<Content>Which of the following statements summarizes the argument of the last paragraph?</Content> 
<Options> 
    <A>Heavy traffic on a miry and dirty road may lead to evil thoughts.</A> 
    <B>The more evil we think, the more vile we are likely to become.</B> 
    <C>Evil people should not be welcomed as guest in our homes the same way as we welcome good people.</C> 
    <D>Evil thoughts control the key to the human heart and no one can keep the out.</D> 
</Options> 

+0

花一點時間瞭解序列化如何工作意味着什麼這些帖子不會讓你感到困惑。 –

+0

你有什麼嘗試......'hireacoder'或自己做,並在這裏如果你有任何麻煩做到這一點.. – Anirudha

回答

4

你可以做到這一點與LINQ to Xml

XDocument xdoc = XDocument.Load(path_to_xml); 
var query = xdoc.Descendants("Question") 
       .Select(q => new Question() 
       { 
        Id = (int)q.Attribute("id"), 
        Content = (string)q.Element("Content"), 
        Options = q.Element("Options") 
           .Elements() 
           .Select(o => (string)o).ToArray() 
       }); 

這將返回IEnumerable<Question>序列,其中問題是這樣一類:

public class Question 
{ 
    public int Id { get; set; } 
    public string Content { get; set; } 
    public string[] Options { get; set; } 
} 
+1

感謝您的回答,而不是將我的問題視爲愚蠢和重複 – murdersp