Solved

Creating, Reading and Updating XML

Posted on 2008-09-29
18
492 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:angus_young_acdc
  • 7
  • 7
  • 3
  • +1
18 Comments
 
LVL 3

Expert Comment

by:R_Janssen
ID: 22597044
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
 
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22597296
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 ();
      }
0
 
LVL 7

Assisted Solution

by:joesthebighmoe
joesthebighmoe earned 100 total points
ID: 22597356
When working with XML and .Net we handle everything with an XML Document.

It is common to map Xml Elements to Objects when we use XML to persists those objects.
So for example, let's say you have an Account Object with the following attributes: ID, Balance, PIN.
It is common for its XML to look like this...
<Account ID="12" Balance="46,501.21" PIN="23411"/>
We could create an Xml Document that holds three accounts like this...
<Accounts>
  <Account ID="12" Balance="46,501.21" PIN="23411"/>
  <Account ID="13" Balance="1,765.33" PIN="88745"/>
  <Account ID="14" Balance="2,000,003" PIN="43779"/>
</Accounts>

This text file can be saved and then reloaded by using the XmlDocument's Load method.
myXmlDoc.Load("C:\UserData.xml")
0
 
LVL 7

Expert Comment

by:joesthebighmoe
ID: 22597401
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.


0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22603494
        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

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22603542
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;
        }
0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22603567
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?
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22603699
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();
}
0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22603741
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;
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22603766
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

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22603767
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
{
}
0
 
LVL 26

Accepted Solution

by:
Anurag Thakur earned 400 total points
ID: 22603781
try to use this
i am searching on the attributes in the xml
if i get the match i will return the balance

XmlNode node = myDoc.SelectSingleNodes("//Accounts/Account[@PIN='" + pinValueToSearch + "' and @ID='" + IdToBeSearched +"']");
if (node != null)
{
    string balance = node.Attributes.GetNamedItem("Balance").Value.ToString();
}
0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22605900
Thanks that worked great.  How can I write to the specific node though?  Again based on the ID.
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22606059
find the node as you have found and do the reverse
node.Attributes.GetNamedItem("Balance").Value = balance;
0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22606161
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

0
 
LVL 7

Assisted Solution

by:joesthebighmoe
joesthebighmoe earned 100 total points
ID: 22606257
myDoc.Save
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22606737
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
0
 
LVL 15

Author Comment

by:angus_young_acdc
ID: 22612357
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!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now