Query a specific node of an XML file in c#

Asked

Viewed 233 times

2

I have a login system in C# and a following XML file:

    <?xml version="1.0"?>
<Usuarios>
    <Usuario>
        <User_ID>001</User_ID>
        <Password>010309</Password>
        <Password_Change_Date>00/00/00</Password_Change_Date>
        <User_Login>admteste</User_Login>
        <User_RG>00000002</User_RG>
        <User_Status>Normal</User_Status>
        <User_Profile>4</User_Profile>
    </Usuario>
    <Usuario>
        <User_ID>002</User_ID>
        <Password>01234</Password>
        <Password_Change_Date>01/10/2019</Password_Change_Date> 
        <User_Login>pbteste</User_Login>
        <User_RG>00000005</User_RG>
        <User_Status>Inicial</User_Status>
        <User_Profile>3</User_Profile>
    </Usuario>  
    <Usuario>
        <User_ID>003</User_ID>
        <Password>01234</Password>
        <Password_Change_Date>21/1/2013</Password_Change_Date>
        <User_Login>pbteste2</User_Login>
        <User_RG>00000023</User_RG>
        <User_Status>Bloqueado</User_Status>
        <User_Profile>3</User_Profile>
    </Usuario>
</Usuarios>

On my system, when the user presses the Login button I need to check in this XML if the login name exists in this file and if the password is according to the user, how can I do it by reading only the User_login and Password nodes ? Thank you

  • 1

    I advise you to browse the options here: https://stackoverflow.com/questions/4752796/how-to-read-xml-in-net

1 answer

2


Follow the example in XPATH to check if there is a Node Usuario with the User_Login and Password desired:

string usuario = "pbteste";
string senha = "01234x";

XmlNodeList nodeList
    = doc.SelectNodes("//Usuario[User_Login[text()='" + usuario + "'] and Password[text()='" + senha + "']]");

if(nodeList.Count == 0)
    MessageBox.Show("Usuário e/ou Senha estão incorretos");
  • What this nodeList returns if there is data in XML?

  • Sorry, I didn’t understand very well what I do with this nodeList variable

  • If nodeList = 0, it means there is no user with login and password informed. I will change the text to make this clear.

  • Perfect brother, thank you so much was exactly what I needed... now for example if I needed to get the User_rg from this logged-on user, how would I do? could you give me some hint? sorry I need to do this tramp to facul and I’m pretty layy with XML

  • 1

    Use nodeList[0].SelectNodes("User_RG")[0].InnerText

Browser other questions tagged

You are not signed in. Login or sign up in order to post.