I have been waging war with XmlDocuments all day. They are winning. I am building a component in .net 2.0 and am therefore forced to use it. Please take a look at this and help me regain some sanity:
private static string UpdateMeterAccessXml(string meterAccess, int childToUpdate, string field, string value)
{
var doc = new XmlDocument();
doc.LoadXml(meterAccess);
var xpath = String.Format("/items/item[{0}]/{1}", childToUpdate, field);
var modNode = doc.SelectSingleNode(xpath);
modNode.InnerText = value;
doc.ReplaceChild(modNode, doc.SelectSingleNode(xpath));
return doc.OuterXml;
}
doc.ReplaceChild yields an ArgumentException ("The node to be removed is not a child of this node.")
I thought that since an XmlDocument was a reference type I wouldn't have to try to swap out nodes, but if I just update the InnerText of the Node I want, doc.OuterXml doesn't reflect the change.
I think the error message is quite clear, the doc object means the whole document, according to your xpath, "doc.SelectSingleNode(xpath)" is not doc's child, it's descendant instead, so it throws the exception.
You can update the InnerText of the node, doc.OuterXml will reflect the change. The following code works fine for me:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
string xPath = "/book/title";
XmlNode node = doc.SelectSingleNode(xPath);
node.InnerText = "new title";
Console.WriteLine(doc.OuterXml); //it's changed