如何使用LINQ将属性值检索到类中?

时间:2013-12-10 15:45:08

标签: xml linq

这是我的XML文件的部分视图:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<server xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="udsServerInfo.xsd" id="57672acc-4ba7-4876-811a-1629eca853ed" productPath="C:\Tools\ServerInfo\" osActivated="true">
  <networkAdapters>
    <networkAdapter id="6ad45274-6077-4a46-9b5c-d4e7be712310"...

我能够检索所有属性值但不确定使用哪种方法将每个属性值(“productPath”,“id”等)用于我的类

    TextReader tr = new StringReader(xml);
    XDocument doc = XDocument.Load(tr);
    var server = from node in doc.Descendants("server").Attributes()
                    select new Server
                    {
                        serverId = node.???? <= need the attribute "id" here
                        serverProductPath = node. <= "productPath
                    };

谢谢

1 个答案:

答案 0 :(得分:1)

var servers = doc.Descendants("server")
    .Select(x=> new Server{id = x.Attribute("id").Value}).Tolist();