public void AddNodeToXml(string helpid, string fileName)
{
const string STR_EXPRESSION = "/Form/Controls/Control";
XPathDocument doc = null;
try
{
doc = new XPathDocument(fileName);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
if (doc != null)
{
XPathNavigator navigator = doc.CreateNavigator();
XPathNodeIterator localIterator = navigator.Select(STR_EXPRESSION);
while (localIterator.MoveNext())
{
if (localIterator.Current != null)
{
if (localIterator.Current.Name.Equals("Control"))
{
localIterator.Current.MoveToFirstAttribute();
if (localIterator.Current.Value.Equals(helpid))
{
localIterator.Current.MoveToParent();
localIterator.Current.CreateAttribute(string.Empty, "NewAttribute", string.Empty, "value");
}
}
}
}
}
}
My xml structure is as show in STR_EXPRESSION
I want to add new attribute to the control node if currnet cotrol name attribute value is “helpid”,I tried using CreateAttribute() this method but it gives an exception as System.NotSupportedException.
this would be so much easier with Linq to XML, is there any reason you aren’t using it?
This is untested code I wrote off the top of my head, but it should be pretty close, it shows how you would use Linq to solve the same problem: