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");
}
}
}
}
}
}
我的xml结构如STR_EXPRESSION中所示 如果currnet cotrol name属性值为“helpid”,我想向控制节点添加新属性,我尝试使用CreateAttribute()此方法,但它给出了一个异常,如System.NotSupportedException。
答案 0 :(得分:1)
使用Linq to XML会更容易,你有没有理由不使用它?
这是我编写的未经测试的代码,但它应该非常接近,它显示了如何使用Linq来解决同样的问题:
XElement root = XDocument.Load(fileName).Root; //get the root element of the XML document
foreach (var controlElement in root.Descendants("Control").Where(c=>c.Attributes[0] != null && c.Attributes[0].value == helpId)) //get all of the control elements with the appropriate helpid value
{
if (controlElement.Parent == null) continue; // it's always good to be defensive
controlElement.Parent.Attributes.Add("NewAttribute", string.Empty);
}