Edit value within an XML node with C#

Asked

Viewed 839 times

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 make the password change, how can I make this change inside the XML file in the specific node of the logged in user? Assuming I already have the User_id saved in the object... Thank you

  • You can re-read the file with Xdocument and Linq and then save again ...

  • Sorry buddy, I’m pretty layy with XML, could you give me some simple example please ?

  • Put the code that reads?

1 answer

2


One way to change a given node of an XML document is by using Xpath to create a query and select the node you want to change.

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

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

and made a check to see if it is not null, before applying the change in the specific node:

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

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

xmlDoc.Save(strMeuArquivo);

See working on .NET Fiddle.

Supplementary reading on XML.

  • This check which is to see if it is null, is to see if the query returned any results? ps: It worked here, thankful!

Browser other questions tagged

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