• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 507
  • Last Modified:

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
0
angus_young_acdc
Asked:
angus_young_acdc
  • 7
  • 7
  • 3
  • +1
3 Solutions
 
R_JanssenCommented:
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
 
Anurag ThakurTechnical ManagerCommented:
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
 
joesthebighmoeCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
joesthebighmoeCommented:
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
 
angus_young_acdcAuthor Commented:
        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
 
Anurag ThakurTechnical ManagerCommented:
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
 
angus_young_acdcAuthor Commented:
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
 
Anurag ThakurTechnical ManagerCommented:
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
 
angus_young_acdcAuthor Commented:
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
 
angus_young_acdcAuthor Commented:
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
 
Anurag ThakurTechnical ManagerCommented:
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
 
Anurag ThakurTechnical ManagerCommented:
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
 
angus_young_acdcAuthor Commented:
Thanks that worked great.  How can I write to the specific node though?  Again based on the ID.
0
 
Anurag ThakurTechnical ManagerCommented:
find the node as you have found and do the reverse
node.Attributes.GetNamedItem("Balance").Value = balance;
0
 
angus_young_acdcAuthor Commented:
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
 
joesthebighmoeCommented:
myDoc.Save
0
 
Anurag ThakurTechnical ManagerCommented:
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
 
angus_young_acdcAuthor Commented:
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

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 7
  • 7
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now