c#XML到达节点

时间:2015-02-04 12:38:33

标签: c# xml

我需要根据这个条件查询。如果“标题”包含单词“Love”,那么我需要获得相关的电影名称

<mmReply command="getSongsByQuery" userData="hello" status="ok">
<contents>
<songList recordCount="3">
  <song songId="83">
    <field id="12" name="Run Time">03:42</field>
    <field id="102" name="Artist">Ten Years After</field>
    <field id="103" name="Title">I'd Love To Change The World</field>
    <field id="104" name="Movie">Movie Name</field>
  </song>
  <song songId="81">
    <field id="12" name="Run Time">03:08</field>
    <field id="102" name="Artist">Stephen Stills</field>
    <field id="103" name="Title">Love The One You're With</field>
    <field id="104" name="Movie">Movie Name</field>
  </song>
  <song songId="54">
    <field id="12" name="Run Time">05:30</field>
    <field id="102" name="Artist">Led Zeppelin</field>
    <field id="103" name="Title">Whole Lotta</field>
    <field id="104" name="Movie">Movie Name</field>
  </song>
</songList>

下面我不知道如何获取电影

(from c in data.Descendants("song")
               from fld in c.Elements("field")
               where fld.Value.ToLower().Contains("love") && getSeconds(c.Element("field").Value) > 120 //120 is song length
               select new SongInfo()
               {
                   songId = Convert.ToInt32(c.Attribute("songId").Value),
                   song = fld.Value, // keyword.song,
                   Movie = ?????
                   songDuration = getSeconds(c.Element("field").Value),
                   counts = keyword.counts,
                   tweetDateTime = keyword.tweetDateTime
               }).FirstOrDefault();

1 个答案:

答案 0 :(得分:0)

嗯,这可以通过LINQ to XML轻松完成(因为您已在代码中使用它),如下所示:

var songs = data.XPathSelectElements("/mmReply/contents/songList/song/field[@name='Title']")
    .Where(x => x.Value.Contains("Love"))
    .Select(x => new {
                        songID = x.Parent.Attribute("songId").Value, 
                        movieName = x.Parent.XPathSelectElement("field[@name='Movie']").Value
                     }
            );

在此示例data中是XDocument的实例,其中加载了您的xml内容(请注意,您的示例x​​ml格式不正确,因为它错过了</contents></mmReply>结束标签)。

请注意,为了简单起见,我正在创建匿名类型的IEnumerable,您应该创建SongInfo实例。