0

我有以下 xml 架构。

<Rooms>
    <Room RoomNumber="room1" EMAIL="ssds@dsfd.com" dsfdd=""/>
    <Room RoomNumber="room2" EMAIL="ssds@sdd.com" dsfdd=""/>
</Rooms>

我必须根据输入返回电子邮件地址(程序的输入是房间号)。

我如何使用 LINQ to XML 来实现这一点?

4

2 回答 2

2

试试这个:

var xml = XElement.Parse("<Rooms>"+
                "<Room RoomNumber=\"room1\" EMAIL=\"ssds@dsfd.com\" dsfdd=\"\"/>"+
        "<Room RoomNumber=\"room2\" EMAIL=\"ssds@sdd.com\" 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();
于 2013-03-07T09:39:25.023 回答
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();
于 2013-03-07T09:51:53.880 回答