2010-06-29 111 views
2

我有一個XML文件(sample.xml中),它具有以下結構如何在C#中使用LINQ的XML文件中刪除特定節點

<RootElement>  
     <Child Name="FirstChild" Start="1" End="2"/> 
     <Child Name="SecondChild" Start="0" End="2"/>   
     <Child Name="ThirdChild" Start="1" End="2"/>    
     <Child Name="FourthChild" Start="0" End="2"/>    
     <Child Name="FifthChild" Start="0" End="2"/>    
     <Child Name="SixthChild" Start="1" End="2"/> 
     <MatchedChilds> 
      <Child Name="FirstChild" /> 
      <Child Name="SecondChild" /> 
      <Child Name="ThirdChild" /> 
      <Child Name="FourthChild" /> 
      <Child Name="FifthChild" /> 
      <Child Name="SixthChild" /> 
    </MatchedChilds> 
</RootElement> 

我需要刪除,如果它的元素「孩子」是直屬「rootElement的」

請給我一個XML到LINQ計算策略做這個

回答

1
 XDocument X_DOC = XDocument.Load(Application.StartupPath + "\\Sample.xml"); 
     X_DOC.Root.Elements("Child").Remove(); 
     X_DOC.Save(Application.StartupPath + "\\Sample.xml"); 
+0

你應該調用'Path.Combine'。另外,您不需要「Where」呼叫。 – SLaks 2010-06-29 12:00:03

+0

@ SLaks:請發表示例代碼 – 2010-06-29 12:02:22

+0

@ SLaks:謝謝.....編輯於(第2行)。謹發帖子爲 Path.Combile – 2010-06-29 12:07:56

2

您需要遍歷所有的節點並刪除它們,就像這樣:

foreach(var child in root.Elements("Child").ToArray()) 
    child.Remove(); 

Elements調用將返回您調用它的元素的所有直接子元素;它不會歸還孫子;

您必須致電ToArray,否則在列舉它時您將修改該集合。

相關問題