This is probably something extremely simple but I can’t get my head around it so help would be appreciated 🙂
I have a simple XML file that I’d like to parse and I have a problem accessing element’s values.
This is the XML document I have:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<application>
<description>
<![CDATA[ This is the description of the application. ]]>
</description>
<parameters>
<param type="int32" name="testvar1" required="false">10</param>
<param type="string" name="testvar2" required="true" />
<param type="float" name="testvar3">42.00</param>
</parameters>
</application>
I load the document from a textbox, like:
var doc = XDocument.Parse(textBox1.Text);
And I use a simple Linq query to filter out stuff:
var parameters = from param in doc.Descendants("param")
select new
{
name = (String)param.Attribute("name"),
type = (String)param.Attribute("type"),
value = (String)param.Value, // Wrong?
};
var data = String.Empty;
foreach (var p in parameters)
{
data += p.name;
data += " -- ";
data += p.type;
data += " -- ";
data += p.value;
data += "\n\r";
}
The output looks like:
testvar1 -- int32 --
testvar2 -- string --
testvar3 -- float --
In other words, the line value = (String)param.Value doesn’t seem to have the desired effect.
EDIT: It seems like I wasn’t reading the correct XML file, my bad. The question below is still valid though…
Also, the following lines causes a NullReferenceException:
var description = (String) doc.Element("description").Value;
So it looks like I don’t quite understand how to get the value of XML elements 🙂 Could you help me fix these?
Thanks.
I was having problems with:
or
but this one seems to work: