2012-01-20 10 views
0
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構造は、私は - オンライン・クロックcotrol name属性の値が「helpidに」であれば制御ノードに新しい属性を追加したいSTR_EXPRESSION でshowようですSystem.NotSupportedExceptionをスローし、私はcreateAttributeを()このメソッドを使用してみましたSystem.NotSupportedExceptionとして例外が発生します。createAttributeをメソッドが

+0

あなたが使用していない理由を ' XDocument'とLINQ to XML? – Oded

+0

理由がない、これはもっと簡単だと思った –

答えて

1

これはLinqで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); 
} 
+0

私はGetXml()fucntionについて少し混乱させてくれますか? –

+1

私の更新を見てください、これはxml文書をロードし、ルート要素を与えるべきです – Jason

+0

c => c.Attributes [0]はエラーをエラーとして返します。[]を使用したインデックス付けを 'method group'タイプの式に適用できません。 –

関連する問題