Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote a program in C# to read settings from an XML file

XML
<?xml version="1.0" encoding="UTF-8"?>
-<settings><setting2>4</setting2><setting3> </setting3><setting4> </setting4><setting5> </setting5><setting6> </setting6><setting7> </setting7><setting8> </setting8><setting9> </setting9><setting10> </setting10><setting11> </setting11><setting12> </setting12><setting13> </setting13><setting14> </setting14><setting15> </setting15><setting16> </setting16><setting17> </setting17></settings>


Now i want to load it in program with

C#
string xmlfilename = Path.Combine(Application.StartupPath, filename);
XDocument doc = new XDocument();
 XDocument.Load(xmlfilename);
textBox1.Text + doc.Root.Element("settings").Element("setting2").Value;


But it gives error object reference not set to an instance of an object.
Posted
Updated 2-Oct-15 1:16am
v2

From your code, xml file was not loading to doc object and secondly you are getting error due to root element. Please try with below code:
C#
Document doc = XDocument.Load(xmlfilename);
// This is one way to fetch XML data
string temp = textBox1.Text + doc.Root.Element("setting2").Value;
// or
// Another way to fetch XML data
string temp = textBox1.Text + doc.Element("settings").Element("setting2").Value;
 
Share this answer
 
Comments
[no name] 2-Oct-15 7:12am    
The first one you wrote did work well
My code was exactly the second one
Maciej Los 2-Oct-15 7:20am    
5ed!
1. Try with XmlDocument

2. Go one step at a time (XmlElement root = doc.Root; root.Element(settings) etc.) until you get which returns null

3. Instead of going .Element.Element.Element write XPath to wanted element (//settings/setting2)

Some of this should resolve the problem, play a bit with the code.

Here is complete example: Parse XML Documents by XMLDocument and XDocument[^]
 
Share this answer
 
v2
Comments
Maciej Los 2-Oct-15 7:20am    
5ed!

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