我有以下xml架構。如何使用LINQ to XML獲取xml的屬性值?
<Rooms>
<Room RoomNumber="room1" EMAIL="[email protected]" dsfdd=""/>
<Room RoomNumber="room2" EMAIL="[email protected]" dsfdd=""/>
</Rooms>
我必須根據輸入返回電子郵件地址(輸入到程序是房間號碼)。
如何使用LINQ to XML實現這一點?
我有以下xml架構。如何使用LINQ to XML獲取xml的屬性值?
<Rooms>
<Room RoomNumber="room1" EMAIL="[email protected]" dsfdd=""/>
<Room RoomNumber="room2" EMAIL="[email protected]" dsfdd=""/>
</Rooms>
我必須根據輸入返回電子郵件地址(輸入到程序是房間號碼)。
如何使用LINQ to XML實現這一點?
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();
試試這個:
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();
謝謝MarcinJuraszek。它的工作。 – PaRsH 2013-03-07 09:59:31