【发布时间】:2016-05-09 19:56:09
【问题描述】:
我有一个这样的 xml 文件:
<?xml version="1.0" encoding="utf-8" ?>
<LogOnUsersInfo>
<GeneralInformation>
<NumberOfUsers>2</NumberOfUsers>
<LastUser UserName="User1"/>
</GeneralInformation>
<LogOnUserCollection>
<LogOnUser UserName="User1" Password="password">
<Rights>
<CanCreateProducts value="true"/>
<CanEditProducts value="true"/>
<CanDeleteProducts value="true"/>
<CanCreateLogIns value="true"/>
<CanDeleteLogIns value="true"/>
<CanBeDeleted value="true"/>
<HasDebugRights value="false"/>
</Rights>
</LogOnUser>
<LogOnUser UserName="User2" Password="password">
<Rights>
<CanCreateProducts value="true"/>
<CanEditProducts value="true"/>
<CanDeleteProducts value="true"/>
<CanCreateLogIns value="true"/>
<CanDeleteLogIns value="true"/>
<CanBeDeleted value="true"/>
<HasDebugRights value="false"/>
</Rights>
</LogOnUser>
</LogOnUserCollection>
</LogOnUsersInfo>
我有一个类,其属性与所述 xml 文件中的值相匹配:
public class LogOnUser
{
#region NestedTypes
public class Rights
{
public bool CanCreateProducts { get; set; }
public bool CanEditProducts { get; set; }
public bool CanDeleteProducts { get; set; }
public bool CanCreateLogIns { get; set; }
public bool CanDeleteLogIns { get; set; }
public bool CanBeDeleted { get; set; }
public bool HasDebugRights { get; set; }
};
#endregion
#region Members
string _UserName;
string _Password;
bool _LoggedIn;
Rights _UserRights;
#endregion
#region Construction
public LogOnUser() { }
public LogOnUser(string username)
{
_UserName = username;
}
public LogOnUser(string username, string password, bool cancreateproducts, bool caneditproducts, bool candeleteproducts, bool cancreatelogins, bool candeletelogins)
{
_UserName = username;
_Password = password;
_UserRights = new Rights();
_UserRights.CanCreateProducts = cancreateproducts;
_UserRights.CanEditProducts = caneditproducts;
_UserRights.CanDeleteProducts = candeleteproducts;
_UserRights.CanCreateLogIns = cancreatelogins;
_UserRights.CanDeleteLogIns = candeletelogins;
}
#endregion
#region Properties
public string Username
{
get { return _UserName; }
set { _UserName = value; }
}
public string Password
{
get { return _Password; }
set { _Password = value; }
}
public bool LoggedIn
{
get { return _LoggedIn; }
set { _LoggedIn = value; }
}
public Rights UserRights
{
get { return _UserRights; }
set { _UserRights = value; }
}
#endregion
}
我尝试使用 XDocument 将 xml 文件中的某些值读取到我的 LogOnUser 类的实例中,但是在浏览 MSDN 上的文档并没有找到我正在寻找的内容之后,我变得有点卡住了认为在这里提出问题可能会更快更容易。
基本上,我刚开始尝试将 XML 中的 UserName 字段读取到 LogOnUser 对象的 UserName 属性中。我试过这个:
var XMLUser = XElement.Load(LogOnUserXMLFilePath);
foreach(XElement e in XMLUser.DescendantsAndSelf())
{
var user = new Model.LogOnUsers.LogOnUser(e.Name.ToString());
}
但是,这会将UserName 设置为“LogOnUsersInfo”,所以显然我需要更深入地了解 xml,但我不知道如何。
谁能指出我正确的方向?
【问题讨论】:
标签: c# xml linq-to-xml