2013-03-07 143 views

回答

1
var doc = XDocument.Load(myXmlFilePath); 
// or doc = XDocument.Parse(myXmlString); 

string roomNumber = "room1"; 

var emailQuery = from room in doc.Root.Elements("Room") 
       where (string)room.Attribute("RoomNumber") == roomNumber 
       select (string)room.Attribute("EMAIL"); 

然後,就像你可以得到結果的查詢:

// if there is always only one <Room> with given roomNumber 
var email = emailQuery.First(); 
// otherwise 
var emails = emailQuery.ToList(); 
+0

謝謝MarcinJuraszek。它的工作。 – PaRsH 2013-03-07 09:59:31

2

試試這個:

var xml = XElement.Parse("<Rooms>"+ 
       "<Room RoomNumber=\"room1\" EMAIL=\"[email protected]\" dsfdd=\"\"/>"+ 
     "<Room RoomNumber=\"room2\" EMAIL=\"[email protected]\" dsfdd=\"\"/>"+ 
       "</Rooms>"); 

string room = "room1"; //input 
var email = xml.Elements("Room") 
         .Where(c => c.Attribute("RoomNumber").Value == room) 
         .Select(c => c.Attribute("EMAIL").Value).FirstOrDefault(); 
+0

它不會工作。我的問題是,如果我給「房間1」輸入,我必須得到[email protected],如果我/ P是「房間2」,那麼o/p應該是「[email protected]」。在此先感謝 – PaRsH 2013-03-07 09:42:44

+0

@PaRsH確定sry,我已更新答案 – 2013-03-07 09:45:44

+0

謝謝Jens。我得到了解決方案。 – PaRsH 2013-03-07 09:58:48