Link to home
Start Free TrialLog in
Avatar of angus_young_acdc
angus_young_acdcFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Creating, Reading and Updating XML

I am wondering how to create an XML file (to get away from StreamReader) for the following details:
Account ID:
Account Balance:
PIN:
(the above would be for around 5 users)

But I am rather stuck on how its actually meant to look in XML.  Also I need to try and find out how to read those values, and also update them depending on the PIN number entered.

All help is greatly appreciated
Avatar of R_Janssen
R_Janssen
Flag of Netherlands image

See XML as a Treeview, Parents and childs.. with some extra info in between.
Example on how to read/write C# @ http://www.c-sharpcorner.com/uploadfile/mahesh/readwritexmltutmellli2111282005041517am/readwritexmltutmellli21.aspx
 
this is one of the alternative
might not be one of the best solutions but will work

      string xmlString = "<account><detail id=\"\" balance=\"\" pin=\"\"/></account>";
      XmlDocument doc = new XmlDocument();
      doc.LoadXml(xmlString);

      // setting the values
      XmlNode node = doc.SelectSingleNode("//account/detail");
      if (node != null)
      {
            node.Attributes.GetNamedItem ("id").Value = "1234567890";
            node.Attributes.GetNamedItem ("balance").Value = "1234567890.1234567890";
            node.Attributes.GetNamedItem ("pin").Value = "1234567890";
      }
                  
      //reteriving the values
      node = doc.SelectSingleNode ("//account/detail");
      if (node != null)
      {
            string id = node.Attributes.GetNamedItem ("id").Value.ToString();
            string balance = node.Attributes.GetNamedItem ("balance").Value.ToString ();
            string pin = node.Attributes.GetNamedItem ("pin").Value.ToString ();
      }
SOLUTION
Avatar of joesthebighmoe
joesthebighmoe
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The XmlDocument class also has a related Save method for saving a changed file.

If I wanted to change an Account's PIN I would find the correct Account element and change the PIN attribute and then call the Save method of the XMLDocument.


Avatar of angus_young_acdc

ASKER

        Based on the XML example above where my XML doc contains only this:
         <Accounts>
        <Account ID="001354145" Balance="2500.21" PIN="1234"/>
        <Account ID="002314515" Balance="500.33" PIN="5678"/>
        <Account ID="005869849" Balance="6000.00" PIN="9012"/>
        </Accounts>
         
And I have the reader code in the snippet above, what am I doing wrong to get a null value?  The node states that it is null.
        public string ReadXML()
        {
 
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(@"C:\Projects\Accounts.xml");
 
            XmlNode node = myDoc.SelectSingleNode("//Accounts/Account ID");
            if (node != null)
            {
                id = node.Attributes.GetNamedItem("ID").Value.ToString();
 
            }
            return id;
        }

Open in new window

change to follwowing because
the node name is Account and ID is an attribute
XmlNode node = myDoc.SelectSingleNode("//Accounts/Account");

        public string ReadXML()
        {
 
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(@"C:\Projects\Accounts.xml");
 
            XmlNode node = myDoc.SelectSingleNode("//Accounts/Account");
            if (node != null)
            {
                id = node.Attributes.GetNamedItem("ID").Value.ToString();
 
            }
            return id;
        }
Thanks that works much better, but as that returns just the first value for the node how can I do a check on all accounts in the document?  Like based on the ID number do a search through them all until I found the correct one, then check the PIN against that ID?
try to use this
instead of node use nodelist

XmlNodeList list = myDoc.SelectNodes("//Accounts/Account");
XmlNode node;
for (int i = 0; i < list.Count; i++)
{
     node = list[i];
     id = node.Attributes.GetNamedItem("ID").Value.ToString();
}
Thanks that does indeed return all of the account IDs in the XML doc, but is there a method whereby to check the pin is correct for that person?

By that I mean having something like this pseudo code:
         
             foreach(ID in the list)
                if the submittedPin == actualPin
                    return true;
                else
                    return false;
I have tried the code below, but I get a nullref exception on pin = node...

        public string ReadXML()
        {
            string userId = "001354145";
            string enteredPin = "1234";
          
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(@"C:\Projects\ATM Project\Accounts.xml");
            XmlNodeList list = myDoc.SelectNodes("//Accounts/Account");
            XmlNode node;
            for (int i = 0; i < list.Count; i++)
            {
                node = list[i];
                id = node.Attributes.GetNamedItem("ID").Value.ToString();   // id is a string
                pin = node.Attributes.GetNamedItem("PIN").Value.ToString(); // pin is a string
                if (userId == id && enteredPin == pin)
                {
                    balance = node.Attributes.GetNamedItem("Balance").Value.ToString();
                }
         
            }
            return balance;  // string

Open in new window

if you want to search for a particular pin in the xml you can do that by

XmlNodeList list = myDoc.SelectNodes("//Accounts/Account[@PIN='" + pinValueToSearch + "']");
if (list != null && list.Count == 1) //if only one pin matches in the xml take what action you want to take
{
}
else
{
}
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks that worked great.  How can I write to the specific node though?  Again based on the ID.
find the node as you have found and do the reverse
node.Attributes.GetNamedItem("Balance").Value = balance;
I had tried that, code listed below, but it doesn't seem to update the XML file.  Although it doesn't throw an error.
public bool UpdateCustomerDetails(string userId, string amount)
        {
           
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(@"C:\Projects\ATM Project\Accounts.xml");
            XmlNode node = myDoc.SelectSingleNode("//Accounts/Account[@ID='" + userId + "']");
            if (node != null)
            {
                string balance = node.Attributes.GetNamedItem("Balance").Value.ToString();
 
                decimal originalBalance = Decimal.Parse(balance);
                decimal amountTaken = Decimal.Parse(amount);
                decimal convertBalance = originalBalance - amountTaken;
 
 
                node.Attributes.GetNamedItem("Balance").Value = convertBalance.ToString();
               
                return true;
            }
            else
            {
              
                return false;
 
            }
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
before yiu return true you say
 myDoc.Save(@"C:\Projects\ATM Project\Accounts.xml");

to overrite the existing file or someother file name so save to a different file
Haha ah what an idiot, I didn't even think to check that there was actually a method to ensure its saved not just temp updated.  What can I say it was a long day!

Cheers guys, your help has definately been appreciated.  Benefit being that whereas I had many, many, MANY lines of code to read a text file, trim the data, check it and then save it I can now do it very quickly in XML!