2014-11-25 130 views
0

我在解析XML文檔以獲取我想要的數據時遇到了一些麻煩。我有這個XML文件:從XML中選擇屬性

<root response="True"> 
    <movie title="Spider-Man 2" year="2004" rated="PG-13" runtime="127 min" 
    genre="Action, Adventure" director="Sam Raimi" 
    actors="Tobey Maguire, Kirsten Dunst, James Franco, Alfred Molina" 
    metascore="83" type="movie" /> 
</root> 

我有一些麻煩,因爲我想保存這些屬性,我真的不知道如何。我試過使用XmlElement類和SelectSingeNode方法,但我似乎無法使其工作。什麼香港專業教育學院嘗試迄今:

root.SelectSingleNode(@"\\movie[title]).InnerText;

,但我不斷收到以下錯誤:

System.Xml.XPath.XPathException'\\\\movie[@genre]' has an invalid token.

我希望能夠保存,例如,的標題電影。我能做些什麼不同?

+0

請張貼錯誤。同時發佈期望的輸出。 – 2014-11-25 02:40:11

+0

修改爲包含錯誤和期望的結果。 – Ultracoustic 2014-11-25 02:45:37

+0

'root.SelectSingleNode(「// movie」)。Attributes [「title」]。Value'? – Prescott 2014-11-25 02:55:50

回答

1

試試這個來獲得所需屬性的值,例如標題:

root.SelectSingleNode("/root/movie/@title").Value 
1

這只是一個舉例來說,我建議你做一個類來代替,但是這應該爲你工作:

foreach (XmlElement movie in root.SelectNodes("//movie")) 
    { 
     string title = string.Empty; 
     string year = string.Empty; 
     //etc 
     title = movie.Attributes["title"] != null ? movie.Attributes["title"].Value : string.Empty; 
     //etc 
    }