2015-08-15 35 views
0

選擇值我有這樣的XML:查詢中的XElement

<?xml version="1.0" encoding="utf-8"?> 
    <Words> 
    <List> 
     <Cid Name="c1" ID="11"> 
      <Word Name="test1" ID="1"> 
      <Name>test1</Name> 
      <Link>yahoo.com</Link> 
      </Word> 
     </Cid> 
     <Cid Name="c2" ID="22"> 
      <Word Name="w0" ID="0"> 
      <Name>test0</Name> 
      <Link>yahoo0.com</Link> 
      </Word> 
      <Word Name="w1" ID="1"> 
      <Name>test</Name> 
      <Link>yahoo.com</Link> 
      </Word> 
      <Word Name="w1" ID="2"> 
      <Name>mehrdad</Name> 
      <Link>google.com</Link> 
      </Word> 
     </Cid> 
     </List> 
    </Words> 

我想搜索的詞,如果節點存在獲取名稱和鏈接
所以我嘗試搜索與此代碼

XDocument doc = XDocument.Load(data); 

      var relatedDocs = 
       from CatID in 
       doc.Elements("Cid") 
        .Where(x => (string)x.Attribute("ID").Value == ctId.ToString()) 
        .Select(x => x.Elements("Word")) 
        .Where (What is here ? don have access to Attribute so what ?) (x => x.Attribute("Name").Value == sName) 

        select new SelectWord { 
         NameAtt = CatID.Attribute("Name").Value, 
         IDAtt = CatID.Attribute("ID").Value, 
         Name = CatID.Element("Name").Value, 
         Link = CatID.Element("URL").Value 
        }; 

,這是SelectWord類

class SelectWord 
     { 
      public string NameAtt { get; set; } 
      public string IDAtt { get; set; } 
      public string Name { get; set; } 
      public string Link { get; set; } 
     } 

始終把結果爲空!
我想我的查詢是錯誤的,需要改變什麼?

回答

1

請試試這個:

var relatedDocs = 
    from CatID in doc.Root.Element("List").Elements("Cid") 
     .Where(x => x.Attribute("ID").Value == ctId.ToString()) 
     .SelectMany(x => x.Elements("Word") 
      .Where(w => w.Attribute("Name").Value == sName)) 
    select new SelectWord 
    { 
     NameAtt = CatID.Attribute("Name").Value, 
     IDAtt = CatID.Attribute("ID").Value, 
     Name = CatID.Element("Name").Value, 
     Link = CatID.Element("Link").Value 
    }; 
+0

謝謝,但NOE有一個新的問題!這裏在** Elements **:'.Select(x => x.Elements(「Word」))。Where(這裏屬性是什麼?)(x => x.Attribute不存在)' – Sara

+0

@Sara Corrected 。 –

+0

謝謝,是否有可能得到所有結果點頭,而不是第一個? – Sara