Click here to Skip to main content
15,899,937 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an XML file in string format. The XML file may sometimes contain more that one of the same tags, like it may have multiple msisdn tags. I am using linq to XML to retrieve all of the msisdn's tags values.

I have a class with the property as follow:

private List<int> _msisdn;
public List<int> msisdn
{
   get { return _msisdn; }
   set { _msisdn = value; }
}

when I use a Linq to XML query, I get the error saying:
Object reference not set to an instance of an object.


Here is the linq code:

public void getMsidn(string xml)
        {
            XElement xDoc = XElement.Parse(xml);

            IEnumerable<XElement> da = from p in xDoc.Descendants("msisdn")
                                       select p;

            foreach (XElement x in da)
            {
                _msisdn.Add((int)x);
            }
        }


I want to be able by using this query, add all the values retrieved from the xml to the property mentioned above.

Any help regarding this?
Posted
Updated 14-Mar-12 23:24pm
v3
Comments
Lakxman 15-Mar-12 5:38am    
Can you let me know on what line does this error occurs? is that in Linq query line? If so, can you please check if xDoc is being null or something?
Andrew797 15-Mar-12 5:46am    
I have checked, and the xDoc is not null, it contains the XML file, XElement x is not null, it contains values. the error is given at _msisdn.add((int)x); Is this not maybe because it is expecting me to create a new list, like List<int> _msisdn = new List<int>(); I do not want to do it like that, I want to be able to use the list data type in the property

Try this one

C#
public void getMsidn(string xml)
        {
            XElement xDoc = XElement.Parse(xml);
 
            IEnumerable<xelement> da = from p in xDoc.Descendants("msisdn")
                                       select p;
 
            foreach (XElement x in da)
            {
                msisdn.Add((int)x);
            }
        }
 
Share this answer
 
v2
Comments
Andrew797 15-Mar-12 6:56am    
The same approach as what I have done. Thanks
I have found a solution myself, using the following approach:

my Property:

XML
private IEnumerable<int> _msisdn;
        public IEnumerable<int> msisdn
        {
            get { return _msisdn; }
            set { _msisdn = value; }
        }


And my linq to xml query:

C#
public void getMsidn(string xml)
        {
            XElement xDoc = XElement.Parse(xml);

            _msisdn = from p in xDoc.Descendants("msisdn")
                                       select (int)p;
        }


This works perfectly for what I need it.

Thanks for the help.
 
Share this answer
 

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