confusedandamused confusedandamused - 2 months ago 9
C# Question

NullReferenceException When attempting to update XML C#

I currently have a windows form application which contains a list view that is updated by the user. When the list view is updated it also populates and creates XML for the items and stores it in a hidden text box until a save request is sent.

When a save request is sent I call a function which writes to my external Config file to updated the denoted property.

In total I'm updating 7 settings, but the only one that fails with a NullReferenceException is when I try to update the list view and save the XML

//The values I'm passing in are the path to my config file, the setting I am updating (in this case would be RequiredDocuments), and the string value to update.

public static void UpdateConfigFiles(string p_sPath, string p_sSettingName, string p_sValue)
{
bool blnApplyChanges = false;
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

xmlDoc.Load(p_sPath);
int iCurrentNode = 0;

for (iCurrentNode = 0; iCurrentNode <= xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0].ChildNodes.Count - 1; iCurrentNode++)
if (xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0].ChildNodes[iCurrentNode].Attributes[0].Value.ToString().ToUpper() == p_sSettingName.ToUpper())
{
//This line is where the exception occurs
xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0].ChildNodes[iCurrentNode].ChildNodes[0].InnerText = p_sValue;
blnApplyChanges = true;
}

if (blnApplyChanges)
{
xmlDoc.Save(p_sPath);
FixBlankXMLValues(p_sPath);
}
}


I had added watches to view the values of all of the different nodes, hadn't come across a null value yet, so I am wondering if it is an issue with the way I had structured my XML. Initially I had thought I had been clearing the passed in values when I rebind my ListView, but that turned out to not be the case.

Here is a sample structure of the XML with some redacted information.

Answer
<setting name="RequiredDocuments" serializeAs="String">     
</setting>

has no childNode 'Value' which you want to update.

xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0] = <Project.Properties.Settings>

xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0].ChildNodes[iCurrentNode] =<setting name="RequiredDocuments" serializeAs="String">

xmlDoc.ChildNodes[1]["applicationSettings"].ChildNodes[0].ChildNodes[iCurrentNode].ChildNodes[0] is NULL.