I'm writing a xml file, but when i started to write elements, it comes with some errors, and when i try to read the xml fil by code, it can't find these elements.
<?xml version="1.0" encoding="utf-8" ?>
<options>
<difficulty>
<type name="Easy" health="6" active="0"/>
<type name="Normal" health="4" active="1"/>
<type name="Hard" health="2" active="0"/>
</difficulty>
<soundvolume>
<type name="Sound" value="100"/>
<type name="tempSound" value="100"/>
</soundvolume>
</options>
this is the xml code so far, but i don't want to continue if i can't get it to work.
this is the errors I get:
Could not find schema information for the element 'options'.
and every element has the same error. I use visual studio 2013 and have a Windows Forms Application C# project
This is how i read the xml file:
StreamReader sr = new StreamReader("Options.xml");
String xmlsr = sr.ReadToEnd();
sr.Close();
XElement xDocumentSr = XElement.Parse(xmlsr);
XElement xOptionsSr = xDocumentSr.Element("options");
XElement xDifficultySr = xOptionsSr.Element("difficulty");
foreach (XElement xType in xDifficultySr.Descendants("type"))
{
if(Convert.ToInt32(xType.Attribute("activate").Value) == 1)
{
labDifficulty.Text = xType.Attribute("name").Value;
}
}
the error happens when her:
XElement xOptionsSr = xDocumentSr.Element("options");
and i get this error:
An unhandled exception of type 'System.NullReferenceException' occurred in Splash Screen.exe
Additional information: Object reference not set to an instance of an object.
and when in debug mode i can see that the element is = null
Here:
XElement xDocumentSr = XElement.Parse(xmlsr);
XElement xOptionsSr = xDocumentSr.Element("options");
The xDocumentSr
itself options
.So you are looking for options
element inside of itself.You don't need that xDocumentSr.Element("options");
.And you can simplify your code like this:
var xmlDocument = XDocument.Load("Options.xml");
var element = xmlDocument.Root
.Element("difficulty")
.Elements("type")
.FirstOrDefault(x => (int)x.Attribute("active") == 1);
if(element != null)
labDifficulty.Text = element.Attribute("name").Value;