views:

275

answers:

1

How do I check to see if an element exists within a given element before trying to add it?

Background: I have an XDocument X that contains as a child element Flowers which subsequently contains a series of elements that are each named Flower. Each Flower already has 2 child elements and I would like to add a 3rd element called Price. However, I want to check and make sure there's not already an element for Price within the Flower element. How do I do that? Do I even need to check?

+4  A: 

XElement has a HasElements property, which would work if just wanted to know whether any elements existed or not.

For your case, I would use...

XNamespace ns = "http://mynamespace.com";
bool hasPrice = flowerElement.Element(ns + "Price") == null;

..to see if a the price element exists. If not, you can then add it.

Note: if you don't have any namespace set for your XML file, you can use Namespace.None instead of ns.

DanM
right, but each `Flower` element alredy has 2 child elements. I'm trying to see if an element called `Price` already exists as a child element. How can I do that without throwing an exception?
Ben McCormack
@Ben, I edited my answer further. This should not throw an exception.
DanM
Thanks. What's `ns` represent in your code?
Ben McCormack
@Ben, `ns` is the XML namespace for the `Price` element. It's normally just the default namespace. I'll add an example on how to set `ns` to my answer.
DanM