2012-01-20 4 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 구조는 내가 currnet 리부팅 이름 속성 값이 "helpid"인 경우 제어 노드에 새로운 속성을 추가 할 STR_EXPRESSION 에 쇼로입니다 System.NotSupportedException을 던져, 나는 CreateAttribute()이 메소드를 사용하여 시도 그러나 System.NotSupportedException 예외를 제공합니다.CreateAttribute 방법이

+0

당신은'사용하지 않는 이유 :

이 꽤 가까이 있어야 난 내 머리 위로 떨어져 쓴 테스트되지 않은 코드는하지만, 그것은 당신이 같은 문제를 해결하기 위해 Linq에를 사용하는 방법을 보여줍니다 XDocument' 및 LINQ to XML? – Oded

+0

이유가 없으므로 이것이 더 쉬울 것이라고 생각했습니다. –

답변

1

Linq에서 XML을 사용하면이 작업이 훨씬 쉬울 것입니다. 사용하지 않는 이유가 있습니까?

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()에 대해 약간 혼동합니다. 도움을 청합니까? –

+1

내 업데이트를 참조하십시오,이 XML 문서를로드하고 루트 요소를 제공해야합니다. – Jason

+0

c => c.Attributes [0] 오류로 오류를 제공합니다. []와 함께 인덱싱을 '메서드 그룹'형식의 식에 적용 할 수 없습니다 –