I have a xml file which I modify with the following code:
XmlDocument xlDoc = new XmlDocument();
string[] files = Directory.GetFiles("C:\\Program Files (x86)", "Product.config", SearchOption.AllDirectories);
string sfile = files[0];
xlDoc.Load(sfile);
XmlNodeList list = xlDoc.SelectNodes("//dependancy");
XmlNode foundNode = xlDoc.SelectSingleNode("//dependancies//dependancy[@name='Microsoft Windows NT']");
int found = list.Count;
if (foundNode == null)
{
foundNode = xmlElement;
list[found - 1].AppendChild(foundNode);
xlDoc.Save(sfile);
ConfigurationManager.RefreshSection(sfile);
}
foreach (XmlNode node in list)
{
xlDoc.Load(sfile);
try
{//use inserted node}
...
Now before the foreach is executed , I want to reload the XML document, so that the value is in the document. The problem I am experiencing is that the changes are only loaded if the application is restarted. How can I reload the file before moving on to the foreach segment?
That’s some pretty confusing code; I assume
xmlElementis a<dependancy name='Microsoft Windows NT'/>element you have created elsewhere.//in XPath expressions search all elements, so//dependancies//dependancy[@name='Microsoft Windows NT']is the same as//dependancy[@name='Microsoft Windows NT']. Assuming there is already at least one<dependancy .../>element, thenWill insert your
xmlElementas a child inside the last existing<dependancy .../>element; like this:That must be what you have, otherwise
list[found - 1]will crash.That is not correct. You already have the change in
list[found - 1]. The real problem is that is not what you are searching:That searches all children of
list, not children oflist[found - 1]. I am guessing that what you want is:To get that, replace
XmlNodeList list = xlDoc.SelectNodes("//dependancy");with:Replace
list[found - 1].AppendChild(foundNode)with:And
foreach (XmlNode node in list)with:If that is not what you want, please clarify.
The reason you are getting your new
xmlElementwhen you run the program again is becausexlDoc.SelectNodes("//dependancy")searches all nodes, including those in<dependancy .../>.Also, what does “dependancy” mean? Do you mean “dependency”? Misspellings are very, very confusing.