Tom

Replacing an XML field in C #

ok, so I have an xml file that looks like this:

<?xml version="1.0"?>
<Users>
  <User ID="1">
    <nickname>Tom</nickname>
    <password>a password</password>
    <host>anemail@hello.com</host>
    <email>anemail</email>
    <isloggedin>false</isloggedin>
    <permission>10</permission>
  </User>
  <User ID="2">
    <nickname>ohai</nickname>
    <password>sercret</password>
    <host>my@host</host>
    <email>my@email</email>
    <isloggedin>false</isloggedin>
    <permission>1</permission>
  </User>
<Users>

now, firstly, I will have a refund that they have an identification number, so the bad one has a "2". from this I will need to go in and edit the fields in it, and then save the xml. so basically I need to open the file, find the information for User ID = "2" and reinstall xml with VARIOUS values ​​inside user 2 without affecting the rest of the document.

from the subscription database:

  <User ID="2">
    <nickname>ohai</nickname>
    <password>sercret</password>
    <host>my@host</host>
    <email>my@email</email>
    <isloggedin>false</isloggedin>
    <permission>1</permission>
  </User>

// make changes here and end up with

  <User ID="2">
    <nickname>ohai</nickname>
    <password>somthing that is different than before</password>
    <host>the most current host that they were seen as</host>
    <email>my@email</email>
    <isloggedin>false</isloggedin>
    <permission>1</permission>
  </User>

and etc.

Summary: I need to open a text file, return information through an identification number, edit the information, re-save the file. affecting nothing but user 2

~ Thank you!

+3
3

: XmlDocument, .NET 1.x , , XML- :

// create new XmlDocument and load file
XmlDocument xdoc = new XmlDocument();
xdoc.Load("YourFileName.xml");

// find a <User> node with attribute ID=2
XmlNode userNo2 = xdoc.SelectSingleNode("//User[@ID='2']");

// if found, begin manipulation    
if(userNo2 != null)
{
   // find the <password> node for the user
   XmlNode password = userNo2.SelectSingleNode("password");
   if(password != null)
   {
      // change contents for <password> node 
      password.InnerText = "somthing that is different than before";
   }

   // find the <host> node for the user
   XmlNode hostNode = userNo2.SelectSingleNode("host");
   if(hostNode != null)
   {
      // change contents for <host> node 
      hostNode.InnerText = "the most current host that they were seen as";
   }

   // save changes to a new file (or the old one - up to you)
   xdoc.Save("YourFileNameNew.xml");
}

.NET 3.5 , Linq-to-XML, , XML-.

+4

, Linq-to-XML. , .

Linq to XML - / XML-

0

You can use XmlDocument for this:

var doc = new XmlDocument();
doc.Load("1.xml");
var node = doc.SelectSingleNode(@"//User[@ID='2']");
node.SelectSingleNode("password").InnerText="terces";
doc.Save("1.xml");
0
source

Source: https://habr.com/ru/post/1719538/


All Articles