从xml中提取数据

时间:2014-03-02 13:10:48

标签: c# xml

我试图从xml文件中提取数据

<root response="True">
<movie title="True Grit" year="1969" rated="N/A" released="11 Jun 1969" runtime="128 min" genre="Adventure, Western, Drama" director="Henry Hathaway" writer="Charles Portis (novel), Marguerite Roberts (screenplay)" actors="John Wayne, Glen Campbell, Kim Darby, Jeremy Slate" plot="A drunken, hard-nosed U.S. Marshal and a Texas Ranger help a stubborn young woman track down her father's murderer in Indian territory." language="English" country="USA" awards="Won 1 Oscar. Another 7 wins & 5 nominations." poster="http://ia.media-imdb.com/images/M/MV5BMTYwNTE3NDYzOV5BMl5BanBnXkFtZTcwNTU5MzY0MQ@@._V1_SX300.jpg" metascore="N/A" imdbRating="7.4" imdbVotes="26,487" imdbID="tt0065126" type="movie" tomatoMeter="90" tomatoImage="certified" tomatoRating="7.9" tomatoReviews="48" tomatoFresh="43" tomatoRotten="5" tomatoConsensus="N/A" tomatoUserMeter="83" tomatoUserRating="3.8" tomatoUserReviews="24,949" DVD="21 Mar 2000" BoxOffice="N/A" Production="Paramount Home Video" Website="N/A"/>
</root>

我写了代码

var res= doc.Element("year");
MessageBox.Show(""+res);

已加载xml文件,但我在消息框上获取空值 如何从每个节点获取值

2 个答案:

答案 0 :(得分:2)

yearmovie 元素的属性

var year = (int)doc.Root.Element("movie").Attribute("year");

答案 1 :(得分:2)

year不是元素,而是attribute,试试这个:

doc.Descendants("movie").First().Attribute("year").Value;