I’m trying to retrieve values from an XML file and I find some values are empty.
textBox6, textBox7, textBox14 corresponding element attribute values are empty/null. The error message is Null reference error was unhanded . How can fix this??
private void DisplayFile(string path)
{
var doc = XDocument.Load(path);
var ns = doc.Root.GetDefaultNamespace();
var conn = doc.Root.Element(ns + "connection");
textBox1.Text = conn.Element(ns + "sourceId").Value;
var doc1 = XDocument.Load(path);
var ns1 = doc.Root.GetDefaultNamespace();
var conn1 = doc.Root.Element(ns1 + "connectionContext");
}
If a given element is not present in the XML
foo.Element("someNode")will return null. When accessing.Valueyou get a NullReferenceException.In order to avoid this NullReferenceException you need to check if the element is not null.
Example with contextType:
Update:
You try to load the connectionContext node from the root element. But this node is a child of the source node. You need to first load this node: