【发布时间】:2014-01-03 17:45:22
【问题描述】:
对于 LINQ 和 XML 来说真的很陌生。我希望有人能告诉我在尝试从 XElement 中删除子节点时我做错了什么。
这是我的 XML 示例: (我正在尝试删除与用户选择的关系相对应的“关系”)
<Bill>
<Element>
<Name>AccountNumber</Name>
<Regex></Regex>
<Left></Left>
<Right></Right>
<Top></Top>
<Bottom></Bottom>
<Index>0</Index>
<Relations></Relations>
</Element>
<Element>
<Name>BillDate</Name>
<Regex></Regex>
<Left></Left>
<Right></Right>
<Top></Top>
<Bottom></Bottom>
<Index>1</Index>
<Relations>
<Relation>AccountNumber.RightOf.Right.0</Relation>
<Relation>AccountNumber.Below.Top.-10</Relation>
<Relation>AccountNumber.Above.Bottom.-10</Relation>
</Relations>
</Element>
如果我的 WPF GUI,当用户单击删除关系时,我只想从父级中删除该关系。
这是我尝试过的众多方法之一:
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
List<RelationsDetailView> details = (List<RelationsDetailView>)DetailsView.ItemsSource;
XElement parentElement = (from Node in ocrVar.Xml.Descendants("Element")
where Node.Element("Index").Value == ocrVar.SelectedItem.Index.ToString()
select Node).FirstOrDefault();
XElement child = parentElement.Element("Relations").Elements("Relation").Where(xel => xel.Element("Relation").Value == (details[DetailsView.SelectedIndex].Relation)).FirstOrDefault();
child.Remove();
ocrVar.Xml.Save(ocrVar.xmlPath);
}
【问题讨论】:
标签: c# xml wpf linq linq-to-xml