我从数据库获取XML:
<Users>
<User>
<USRID>1234</USRID>
<USERNAME>ABCD</USERNAME>
<ROLES>
<ROLE>
<ROLEID>1</ROLEID>
<ROLENAME>GlobalAdministrator</ROLENAME>
<ISDEFAULTROLE>1</ISDEFAULTROLE>
</ROLE>
<ROLE>
<ROLEID>2</ROLEID>
<ROLENAME>Administrator</ROLENAME>
<ISDEFAULTROLE>0</ISDEFAULTROLE>
</ROLE>
</ROLES>
</User>
<User>
<USRID>2312</USRID>
<USERNAME>XUX</USERNAME>
<ROLES>
<ROLE>
<ROLEID>3</ROLEID>
<ROLENAME>AccountManager</ROLENAME>
<ISDEFAULTROLE>1</ISDEFAULTROLE>
</ROLE>
<ROLE>
<ROLEID>5</ROLEID>
<ROLENAME>Approver</ROLENAME>
<ISDEFAULTROLE>0</ISDEFAULTROLE>
</ROLE>
</ROLES>
</User>
</Users>
这是我填充XML的类结构:
public class Role
{
public string RoleId
{
get;
set;
}
public string RoleName
{
get;
set;
}
public bool IsDefaultRole
{
get;
set;
}
}
public class User
{
public User()
{
UserRoles = new List<Role>();
}
public string UserId
{
get;
set;
}
public string UserName
{
get;
set;
}
public List<Role> UserRoles
{
get;
set;
}
}
我想使用linq填充“User”类。怎么样?
XDocument doc = XDocument.Parse(userXML);
lstUser = (from dem in doc
.Descendants("Users")
.Descendants("User")
select new User
{
UserId = dem.Element("USRID").Value,
UserName = dem.Element("USERNAME").Value,
..............................
}).ToList();
请帮我完成上面的代码。 我要写什么.......部分才能获得这个角色?
答案 0 :(得分:1)
试试这个......
var lstUser = doc.Descendants("Users").Descendants("User")
.Select(dem => new User
{
UserId = dem.Element("USRID").Value,
UserName = dem.Element("USERNAME").Value,
UserRoles = dem.Descendants("ROLES").Descendants("ROLE")
.Select(x => new Role
{
RoleId = x.Element("ROLEID").Value,
RoleName = x.Element("ROLENAME").Value,
IsDefaultRole = x.Element("ISDEFAULTROLE").Value == "1"
})
.ToList()
}).ToList();
答案 1 :(得分:1)
如上所述 - 使用xml serializer。它的实现并不完美,但对大多数情况来说还可以。也可以使用DataMember
属性和DataContractSerializer以及反序列化来实现相同的目标。
答案 2 :(得分:1)
易: -
List<User> users = xdoc.Root.Descendants("User")
.Select(x => new User
{
UserId = x.Element("USRID").Value,
UserName = x.Element("USERNAME").Value,
UserRoles = x.Descendants("ROLE")
.Select(z => new Role
{
RoleId = z.Element("ROLEID").Value,
RoleName = z.Element("ROLENAME").Value,
IsDefaultRole = z.Element("ISDEFAULTROLE").Value == "1" ? true : false
}).ToList()
}).ToList();