0

我有有效的代码:

XML:

<parameters>
    <company>asur_nsi</company>
    <password>lapshovva</password>
    <user>dogm_LapshovVA</user>
</parameters>

代码:

XElement documentRoot = XElement.Load(webConfigFilePath);
var param = from p in documentRoot.Descendants("parameters")
            select new
            {
                company = p.Element("company").Value,
                password = p.Element("password").Value,
                user = p.Element("user").Value
            };

foreach (var p in param)
{
    AuthContext ac = new AuthContext()
    {
        Company = p.company,
        Password = p.password,
        User = p.user
    };
}

但是,我想让它变得更好更短,并想立即返回 AuthContext 类型的对象。我想以某种方式将 AuthContext 对象的创建移动到“选择新”部分。

4

3 回答 3

1
XElement documentRoot = XElement.Load(webConfigFilePath);
var param = from p in documentRoot.Descendants("parameters")
            select new AuthContext()
            {
                Company = p.Element("company").Value,
                Password = p.Element("password").Value,
                User = p.Element("user").Value
            };
于 2012-10-16T08:22:09.997 回答
0
XElement documentRoot = XElement.Load(webConfigFilePath);
var authContexts = (from p in documentRoot.Descendants("parameters")
            select new AuthContext
            {
                Company = p.Element("company").Value,
                Password = p.Element("password").Value,
                User = p.Element("user").Value
            }).ToArray();

只需创建AuthContext而不是匿名类型。

于 2012-10-16T08:22:50.090 回答
0

打扰一下。我刚刚弄清楚如何做我想做的事:

var config = XElement.Load(webConfigFilePath).Descendants("parameters").Single();
AuthContext ac = new AuthContext
{
    Company = config.Element("company").Value,
    Password = config.Element("password").Value,
    User = config.Element("user").Value
};

还是非常感谢。

于 2012-10-16T08:40:01.947 回答