I am programming in C# and working with an XDocument. Want to add an element into the tree if and only if there are no other elements that have the a matching attribute value.
For example, is there a LINQ expression that I can use to look at the element below and see if there already exists a foo element with the same name before I add it?
<people>
<foo Name="Bob"> </foo>
<foo Name="Larry"></foo>
<foo Name="Tom"></foo>
</people>
I want to do something like this...
while(myXDocument.Element("people").Elements("foo").Attribute("Name").Contains(myName))
{
// modify myName and then try again...
}
This should work:
XElement.Any(element => element.Attribute("Name").Value == myName)
It will return true if there's an attribute Name
that equals myName
You may want to look at IEnumerable.Any on the XDocument.Elements. This determines whether any element of a sequence satisfies a condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With