Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I have all of the user information written in an .xml file and I would like to get all of the values for a particular user after I match the id of the user who is logged in currently ?

What I have tried:

C#
public string name;
        public static int id = WindowsFormsApplication5.Settings.Default.logedinuserID;
        public int pin;
        public string address;
        public string phone;
        public int checking_acc_num=0;
        public double checking_acc_Balance=0;
        public int saving_acc_num=0;
        public double saving_acc_Balance = 0;
        private void LoadUSERS()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("USERS.xml");

            {
                if (id != 0)
                {
                    foreach (XmlNode node in doc.DocumentElement)
                    {
                        if (id == int.Parse(node["PIN"].InnerText))
                        {
                            name = node.Attributes[0].Value;
                            pin = int.Parse(node["PIN"].InnerText);
                            checking_acc_num = int.Parse(node["CheckingACC/Num"].InnerText);
                            checking_acc_Balance = int.Parse(node["CheckingACC/Balance"].InnerText);
                            saving_acc_num = int.Parse(node["SavingACC/Num"].InnerText);
                            saving_acc_Balance = int.Parse(node["SavingACC/Balance"].InnerText);
                            address = node["Address"].InnerText;
                            phone = node["Phone"].InnerText;


                        }
                    }
                }
            }
        }



This is My Xml File
<?xml version="1.0" encoding="utf-8" ?>
<root>
<User name ="Kamal Al Nasr">
    <ID>123456</ID>
    <PIN>5100</PIN>
    <Name>Kamal Al Nasr</Name>
    <CheckingACC>
      <Num>52645852</Num>
      <Balance>2500</Balance>
    </CheckingACC>
    <SavingACC>
      <Num>741852</Num>
      <Balance>2000</Balance>
    </SavingACC>
    <Address>3500 John Merritt Blvd, Nashville, TN 37209</Address>
    <Phone>(615) 963-5848</Phone>
    <transactionHistory>
      <t1></t1>
      <t2></t2>
      <t3></t3>
      <t4></t4>
      <t5></t5>
      <t6></t6>
      <t7></t7>
      <t8></t8>
      <t9></t9>
      <t10></t10>
      <t11></t11>
      <t12></t12>
      <t13></t13>
      <t14></t14>
      <t15></t15>
      <t16></t16>
      <t17></t17>
      <t18></t18>
      <t19></t19>
      <t20></t20>
    </transactionHistory>
  </User>
  <User name ="Mike Stewart">
    <ID>123457</ID>
    <PIN>5110</PIN>
    <CheckingACC>
      <Num>8569745</Num>
      <Balance>500</Balance>
    </CheckingACC>
    <SavingACC>
      <Num>741850</Num>
      <Balance>3000</Balance>
    </SavingACC>
    <Address>110 Nevada Ave., Nashville, TN 37219</Address>
    <Phone>(615) 963-5555</Phone>
    <transactionHistory>
      <t1></t1>
      <t2></t2>
      <t3></t3>
      <t4></t4>
      <t5></t5>
      <t6></t6>
      <t7></t7>
      <t8></t8>
      <t9></t9>
      <t10></t10>
      <t11></t11>
      <t12></t12>
      <t13></t13>
      <t14></t14>
      <t15></t15>
      <t16></t16>
      <t17></t17>
      <t18></t18>
      <t19></t19>
      <t20></t20>
    </transactionHistory>
  </User>
  <User name ="Adam Lin">
    <ID>123450</ID>
    <PIN>5111</PIN>
    <CheckingACC>
      <Num>8565478</Num>
      <Balance>4500</Balance>
    </CheckingACC>
    <SavingACC>
      <Num>741844</Num>
      <Balance>2000</Balance>
    </SavingACC>
    <Address>1120 Virginia Ave., Nashville, TN 37210</Address>
    <Phone>(615) 963-4444</Phone>
    <transactionHistory>
      <t1></t1>
      <t2></t2>
      <t3></t3>
      <t4></t4>
      <t5></t5>
      <t6></t6>
      <t7></t7>
      <t8></t8>
      <t9></t9>
      <t10></t10>
      <t11></t11>
      <t12></t12>
      <t13></t13>
      <t14></t14>
      <t15></t15>
      <t16></t16>
      <t17></t17>
      <t18></t18>
      <t19></t19>
      <t20></t20>
    </transactionHistory>
  </User>
 </root>
Posted
Updated 20-Feb-16 2:25am
v3
Comments
VR Karthikeyan 19-Feb-16 23:53pm    
Show your xml file?
coding star 20-Feb-16 1:09am    
I added My XML file

You are trying to use perhaps the worst XML API offered by .NET FCL. This is my short overview of those API:
  1. Use System.Xml.XmlDocument class. It implements DOM interface; this way is the easiest and good enough if the size if the document is not too big.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx.
  2. Use the class System.Xml.XmlTextReader; this is the fastest way of reading, especially is you need to skip some data.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx.
  3. Use the class System.Xml.Linq.XDocument; this is the most adequate way similar to that of XmlDocument, supporting LINQ to XML Programming.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx, http://msdn.microsoft.com/en-us/library/bb387063.aspx.


Another problem of your approach is that your solution is totally ad-hoc and is based on hard-coded immediate constants, "magic strings". This is impossible to properly maintain and hard to develop. This is a big no-no, a well known anti-pattern:
https://en.wikipedia.org/wiki/Anti-pattern#Programming,
Magic string — Wikipedia, the free encyclopedia[^],
see also Magic number (programming) — Wikipedia, the free encyclopedia[^].

What to do? I'm not sure if you are using some XML from unknown source. If you also are to create the XML data, you should better use serialization, instead of dealing with XML by yourself:
Serialization — Wikipedia, the free encyclopedia[^],
Marshalling (computer science) — Wikipedia, the free encyclopedia[^],
Serialization in the .NET Framework[^],
Object Serialization in .NET[^].

The best, most robust and easiest to use way of doing serialization is Data Contract. Please see:
Using Data Contracts[^],
DataContractSerializer Class (System.Runtime.Serialization)[^].

See also my past answers where I advocate Data Contract approach:
how to pass a datacontract from a C#/WCF code to Managed C++[^],
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deserializing list<class object> cause the objects property lose their reference to the objects of the base class[^],
How to implement ICloneable for a List Class?[^].

—SA
 
Share this answer
 
v3
Comments
Maciej Los 20-Feb-16 8:26am    
Sure, a 5!
Sergey Alexandrovich Kryukov 20-Feb-16 11:29am    
Thank you, Maciej.
—SA
Sergey's answer is very useful, because it provides tons of useful information. I'd recommend to read that answer very carefully.

In a short: the best option for you is to use Xml Serailization[^].
Why? Because xml serialization and deserialization provides a way to write objects/data into xml and to read it again into objects/data.


To be able to use XML Serialization/Deserialization, you should define classes - for example:
C#
public class User
{
	private int id = 0;
	private int pin = 0;
	private CheckingACC cacc = new CheckingACC();
	
	public int ID
	{
		get {return id;}
		set {id = value;}
	}

	public int PIN
	{
		get {return pin;}
		set {pin = value;}
	}
	
	public CheckingACC CheckingACC
	{
		get {return cacc;}
		set {cacc = value;}
	}

}

public class CheckingACC
{
	private int n=0;
	private double bal=0.0;

	public CheckingACC()
	{
		//default constructor
	}
	
	public CheckingACC(int _n, double _b)
	{
		n = _n;
		bal = _b;
	}

	public int Num
	{
		get {return n;}
		set {n = value;}
	}
	
	public double Balance
	{
		get {return bal;}
		set {bal = value;}
	}
}


In the same way you should define other classes/properties/members.

For further details, please read these articles:
Examples of XML Serialization[^]
https://support.microsoft.com/en-us/kb/815813[^]
XML Serialization and Deserialization: Part-1[^]
XML Serialization and Deserialization: Part-2[^]
A Complete Sample of Custom Class Collection Serialization and Deserialization[^]


Another way is to use XDocument class together with custom classes - as follow:
C#
	int id = 123456;
	
XDocument xdoc = XDocument.Parse(xcontent);
User u =	xdoc.Descendants("User")
			.Where(x=>(int)x.Element("ID") == id)
			.Select(x=> new User{
				ID = Convert.ToInt32(x.Element("ID").Value),
				PIN = Convert.ToInt32(x.Element("PIN").Value),
				CheckingACC = new CheckingACC{
						Num = Convert.ToInt32(x.Element("CheckingACC").Element("Num").Value),
						Balance = Convert.ToDouble(x.Element("CheckingACC").Element("Balance").Value)
					}
				})
			.SingleOrDefault();
//u variable stores all data 


As you can see, above linq query returns custom class (specific object). The magic is in this peace of code: x=> new User{...}

[EDIT]
I almost forgot to mention that you can return anonymous type:
C#
var query = xdoc.Descendants("User")
            .Where(x=>(int)x.Element("ID") == id)
            .Select(x=> new {
                ID = x.Element("ID").Value,
                PIN = x.Element("PIN").Value,
                CheckingACC_Num = x.Element("CheckingACC").Element("Num").Value,
                CheckingACC_Balance = x.Element("CheckingACC").Element("Balance").Value
                });


Above query returns:
ID     PIN  CheckingACC_Num CheckingACC_Balance
123456 5100 52645852        2500 


Good luck!
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 20-Feb-16 11:32am    
Maciej,

I would like to warn everyone about using System.Xml.Serialization.XmlSerializer.
Data Contract made it obsolete. XmlSerializer is much harder to use, it's more intrusive and doesn't have many features of DataContractSerializer. Seriously, switch to DataContractSerializer or, in some cases, DataContractJsonSerializer...

By the way, I wasn't so active on CodeProject lately because I have a strong crisis with project deadlines (which is about to be finally overcame very soon), and also because I just completed the second version of my own serializer based on concept of Data Contract. We made a very hard decision to develop my own serializer, by some reasons, two of them are better human readability (the immediate purpose is to enter XML data manually or through 3rd-party software) and better performance. The major difficulty is using System.Reflection.Emit, to avoid repeated use of any System.Reflection code. In Microsoft technology, due to this reason, serialization assembles are generated during runtime, but I devised a funny combined approach based on generation of Dynamic methods where all reflected data is frozen in; .NET parts of code written in high-level C# and pars of code in dynamic methods call each other; and none of reflection code remains in high-level code, thus still providing very good performance (on my tests, second write was 14 times faster, and read 22 times faster, on a pretty big model, because first run creates caches reflected information, including a dictionary of dynamic methods per type with all the type members and then this cache is reused). Emit code is quite hard to write, because it required knowledge of IL and hard to debug; it's like Assembly programming, but assembly code can be run under the debugger immediately, but not Emit code, because emitted code is not executed while you emit it...

Too bad this stuff it presently proprietary...

—SA
Maciej Los 20-Feb-16 13:49pm    
If you remember our Skype conversations, we discussed a lot about advantages of DataContract and disadvantages of Xml serializer/deserializer. I agree with you, but for such simple structure of data, Xml serializer should be enough for start.

Custom DataContractSerializer written in high-level C# must be very interesting. What a pity that's this software is legally protected.
Sergey Alexandrovich Kryukov 20-Feb-16 14:10pm    
Not quite. It's exactly the same problem with the small models. It it is small, making it serializeable if the effort which is only more considerable compared to the development of the model code itself, besides, this transformation is intrusive, will require some changes to the data model itself. With Data Contract, this is not the case; you don't modify anything in the model, only add attributes, and this is easier to do than creation of the model itself, no matter how simple it is.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900