简体   繁体   English

使用属性进行LINQ to XML解析

[英]LINQ to XML parsing using attributes

I have an xml file like this: 我有一个像这样的xml文件:

<users>
    <user name="user" password="123" email="test@test.com"/>
</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? 有人可以告诉我如何将值复制到对象吗?

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")
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM