使用属性的 LINQ to XML 解析

发布于 2024-12-01 16:06:27 字数 551 浏览 0 评论 0原文

我有一个像这样的 xml 文件:

<users>
    <user name="user" password="123" email="[email protected]"/>
</users>

我需要编写代码将属性值复制到对象类型变量,但找不到任何适合我需要的内容。我成功编写的代码的某些部分是:

public static UserInfo GetUser()
{
    XDocument users = XDocument.Load(FilePath.UserConfigurationPath);

    UserInfo usersvar = new UserInfo();
}

这里我必须返回对象并将其与文本框值进行比较。

谁能告诉我如何将值复制到对象中?

I have an xml file like this:

<users>
    <user name="user" password="123" email="[email protected]"/>
</users>

I need to write a code to copy the attribute values to a object type variable and I can't find anything which suits my needs. some part of the code which I have successfully written is:

public static UserInfo GetUser()
{
    XDocument users = XDocument.Load(FilePath.UserConfigurationPath);

    UserInfo usersvar = new UserInfo();
}

Here I have to return the object and compare it with a textbox value.

Can anybody please tell me how I can copy the values to the object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2024-12-08 16:06:28

解析所有用户:

IEnumerable<UserInfo> GetUsers()
{
    XDocument users = XDocument.Load(path);

    return from u in users.Descendants("user")
           select new UserInfo
           {
               Name = (string)u.Attribute("name"),
               Password = (string)u.Attribute("password"),
               Email = (string)u.Attribute("email")
           };
}

IEnumerable<UserInfo> users = GetUsers();
UserInfo userUser = users.FirstOrDefault(u => u.Name == "user");

如果文档仅包含一个用户或者您想解析第一个用户:

XElement userElement = users.Descendants("user").FirstOrDefault();
if (userElement != null)
{
    UserInfo user = new UserInfo
    {
        Name = (string)userElement .Attribute("name"),
        Password = (string)userElement .Attribute("password"),
        Email = (string)userElement .Attribute("email")
    };
}

To parse all the users:

IEnumerable<UserInfo> GetUsers()
{
    XDocument users = XDocument.Load(path);

    return from u in users.Descendants("user")
           select new UserInfo
           {
               Name = (string)u.Attribute("name"),
               Password = (string)u.Attribute("password"),
               Email = (string)u.Attribute("email")
           };
}

IEnumerable<UserInfo> users = GetUsers();
UserInfo userUser = users.FirstOrDefault(u => u.Name == "user");

If the document contains exactly one user or you want to parse exactly the first:

XElement userElement = users.Descendants("user").FirstOrDefault();
if (userElement != null)
{
    UserInfo user = new UserInfo
    {
        Name = (string)userElement .Attribute("name"),
        Password = (string)userElement .Attribute("password"),
        Email = (string)userElement .Attribute("email")
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文