简体   繁体   English

从XDocument检索XML元素的序列

[英]Retrieve sequence of XML Elements from XDocument

I have a sample xml as follows 我有一个示例XML,如下所示

<users>
  <user>
    <username>John</username>
    <password>password1</password>
    <id>1234</id>
  </user>
  <user>
    <username>Smith</username>
    <password>password2</password>
    <id>1234</id>
  </user>       
<users>

This XML file is loaded into XDocument object like this.. 这样,此XML文件即被加载到XDocument对象中。

XDocument xDoc = XDocument.Load("Users.xml");

How can I retrieve values of password and id elements by passing username as a parameter to it where username is unique in c#.net 4.0 我如何通过将用户名作为参数传递给密码和id元素的值,而在c#.net 4.0中,用户名是唯一的

You can try the following code snippet (method) to extract the password from Xml doc by passing UserName as parameter: 您可以尝试使用以下代码段(方法)通过将UserName作为参数从Xml doc提取password

public string GetUserPassword(string UserName)
{
    XDocument xDoc = XDocument.Load("Users.xml");
    XmlNodeList _users = xDoc.SelectNodes("//users/user");
    string _pwd = null;
    foreach (XmlNode _node in _users)
    {
        if (_node.SelectSingleNode("username").InnerText == UserName)
        {
            _pwd = _node.SelectSingleNode("password").InnerText;
            break;
        }
    }
    return _pwd;
}

And, similar one to get the id : 并且,获得id类似方法:

public string GetId(string UserName)
{
    XDocument xDoc = XDocument.Load("Users.xml");
    XmlNodeList _users = xDoc.SelectNodes("//users/user");
    string _id = null;
    foreach (XmlNode _node in _users)
    {
        if (_node.SelectSingleNode("username").InnerText == UserName)
        {
            _id = _node.SelectSingleNode("id").InnerText;
            break;
        }
    }
    return _id;
}

For performance optimization you can combine this two methods into one, so the Xml document will be loaded just once while method will return the array string[] _pwdAndId , where _pwdAndId[0] corresponds to the id and _pwdAndId[1] to password. 为了优化性能,您可以将这两种方法组合为一个,因此Xml文档将仅加载一次,而方法将返回数组string[] _pwdAndId ,其中_pwdAndId[0]对应于id,而_pwdAndId[1]于密码。

public string[] GetPasswordAndId(string UserName)
{
    XDocument xDoc = XDocument.Load("Users.xml");
    XmlNodeList _users = xDoc.SelectNodes("//users/user");
    string[] _pwdAndId = new string[2];
    foreach (XmlNode _node in _users)
    {
        if (_node.SelectSingleNode("username").InnerText == UserName)
        {
            _pwdAndId[0] = _node.SelectSingleNode("id").InnerText;
            _pwdAndId[1] = _node.SelectSingleNode("password").InnerText;
            break;
        }
    }
    return _pwdAndId ;
}

Hope this will help. 希望这会有所帮助。 Best regards, 最好的祝福,

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

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