【问题标题】:Edit XML Attribute which is selected based on another Attribute grouped with it编辑基于与其分组的另一个属性选择的 XML 属性
【发布时间】:2015-02-12 20:34:11
【问题描述】:

XML 新手,我不知道如何根据连接到它的另一个 XML 属性来更改我选择的 XML 属性,例如,XML 文件的结构如下:

<userinfo>
    <id username="tommy" password="supersecret" email="email@gmail.com" question="Favourite colour" answer="blue"></id>
    <id username="bobby" password="password123" email="derp@gmail.com" question="Pet name" answer="sally"></id>
    <id username="scotty" password="encrypted" email="herp@gmail.com" question="Favourite colour"  answer="blue"></id>
</userinfo>

我需要根据用户名更改密码值。例如,我有用户名“tommy”,我想将 tommy 的密码更改为我拥有的变量。

我尝试了以下方法,但似乎什么也没做,没有错误,什么也没做:

protected void changePassword(string username, string password)
{
//xmlFile is the XDocument xml file path
    var query = from c in xmlFile.Descendants("id")
                .Where(id => (string)id.Attribute("username") == username)
                select c;

    foreach (XElement id in query)
    {
        id.Attribute("password").Value = password;
    }

    xmlFile.Save(@"xml\filepath\doc.xml");
}

这是基于我所看到的,虽然我还没有看到如何使用“where”来做到这一点,所以“var query”......有点在我看来是有意义的。

这是在 asp.net 中使用的,通过按钮调用:

    protected void btnContinue_Click(object sender, EventArgs e)
    {
        var change = Log.GetUserInfoForgot(username, txtNewPassword.Text); 
    }

在这里我听起来像个菜鸟,但它不会让我只调用该方法,而是将它分配给一个 var,即使它不返回任何内容。这可能也导致了一个问题。

【问题讨论】:

    标签: c# asp.net .net xml


    【解决方案1】:

    对不起,我还没有能力发表评论和要求澄清,所以我提交了这个作为答案。

    您的更改密码方法有效。我无法从您的问题中看出Log.GetUserInfoForgot(...) 方法调用和changePassword 调用之间的相关性。 GetUserInfoForgot 在哪里调用了 changePassword?

    【讨论】:

    • ....我很糟糕,非常糟糕。是的,我在按钮中输入了错误的方法名称,难怪除非我将它设置为变量,否则它不会让我拥有它。所以是的,我的代码确实有效,谢谢:)
    【解决方案2】:

    您是否考虑过放弃 LINQ 查询?

    foreach(var el in xmlDoc.Descendents("id").Where(x => x.Attribute("username").Value == name)
    {
        el.Attribute("Password").Value = password;
    }
    

    【讨论】:

    • 这会在 foreach 内的行上引发空引用错误,尽管传递的变量在那里。
    • 我可以看到发生这种情况的唯一方法是 xmlDoc 变量不在 changePassword 函数的范围内。如果您认为它应该在范围内,请尝试在该行设置一个停止点,并在 VS 在那里暂停调试时将鼠标悬停在变量名上。可以看到变量的内容。如果它显示为 null,请尝试将其与您的用户名和密码字符串一起传递。
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多