Edit value inside a node in XML with C #

0

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>  
 </Usuarios>

After the user logs in, I create an object and save all the data within the attributes of this object, my question is: I have a page where the user can change the password, how can I make this change within the XML file in the user-specific node logged in? Assuming I already have the User_ID saved in the object ... Thanks

    
asked by anonymous 22.11.2017 / 23:14

1 answer

2

One way to change a particular node in an XML document is by using XPath to create a query and select the node you want to change.

In this case, I've stored the node in a XmlNode that serves to represent a single node that has been mapped to an XML, the node was returned by SelectSingleNode() method, see:

XmlNode noPassword = xmlDoc.SelectSingleNode("/Usuarios/Usuario[User_ID=" + "001" + "]/Password");

and I checked to see if it is not null before applying the change to the specific node:

if (noPassword != null)
{
    noPassword.InnerText = "minha_nova_senha";              
}   

You can save changes to the file using the Salve method of the XmlDocument class see:

xmlDoc.Save(strMeuArquivo);

See working at .NET Fiddle .

Further reading about XML .

    
23.11.2017 / 03:21