Reputation: 848
Really new to LINQ and XML. I was hoping someone could tell me what I'm doing wrong in trying to remove a child node from an XElement.
Here is a sample of my XML: (I am trying to remove the "Relation" that corresponds to the user selected relation)
<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>
if my WPF GUI, When a user clicks delete on a relation, I want to remove only that relation from the parent.
This is one of the many things I have tried:
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);
}
Upvotes: 1
Views: 1365
Reputation: 101711
xel.Element("Relation").Value == (details[DetailsView.SelectedIndex].Relation
This condition always return false, maybe you want something like this?
(string)xel.Element("Relation") == (details[DetailsView.SelectedIndex].Relation.ToString())
Upvotes: 2
Reputation: 125660
Your Where
predicate is incorrect. xel
is already the <relation>
element, so you don't have to callElement("Relation")
again.
You should also replace XElement.Value
with (string)XElement
to prevent NullReferenceException
.
.Where(xel => (string)xel == (details[DetailsView.SelectedIndex].Relation))
Or you can use FirstOrDefault
with predicate instead of Where().FirstOrDefault()
chain:
XElement child = parentElement.Element("Relations").Elements("Relation").FirstOrDefault(xel => (string)xel == details[DetailsView.SelectedIndex].Relation);
Upvotes: 3