2012-11-22 87 views
0

一个二级节点,我有以下XML文件:访问XML使用LINQ to XML

<tree> 
    <branchs> 
     <branch id=1> 
      <apple id=1 color=green/> 
      <apple id=2 color=red/> 
     </branch> 
     <branch id=2> 
      <apple id=1 color=green/> 
      <apple id=2 color=red/> 
     </branch> 
    </branchs> 
</tree> 

我想SQL命令从分支ID 1访问的Apple ID#1,和比改变颜色(第一次),然后能够从这个分支中删除这个苹果。

我尝试以下,除去一个苹果,但没有任何结果

XDocument doc = XDocument.Load(myxmlFile); 
var result = (from selectedApples in 
       (from selectedBranch in doc.Element("Branchs").Elements("Branch) 
       where selectedBranch.Attribute("id").Value == 1 
       select selectedBranch) 
       where selectedApples.Attribute("id").Value == 1 
       select selectedApples).ToList(); 

result.ToList().ForEach(apple => apple.Remove()); 

我想我犯了一个错误......我想太多我不那么远的解决方案...

有什么帮助吗?

回答

0

不知道这是最优化的解决方案......但它工作。

XDocument doc = XDocument.Load(myxmlFile); 
var results = from selectedApples in doc.Root.Element("branchs").Descendants() 
       where selectedApples.Attribute("id").Value == 1 
       select selectedApples.Elements("apple"); 

foreach(var result in results) 
    result.Where(a => a.Attribute("id").Value == 1).ToList().Foreach(a => a.Remove()); 

doce.Save(myxmlFile);