Add API to determine if a child is valid for a given element
When trying to modify a document, one needs to know if a particular element can add a particular child before doing so. Before, this was one way of doing so which is no longer works:
public static bool CanAddChild<T>(this OpenXmlElement element)
{
if (element == null)
return false;
var attributes = element.GetType().GetCustomAttributes<ChildElementInfoAttribute>();
return attributes.Any(r => r.ElementType == typeof(T));
}
There does not appear to be a way to do this anymore as all of the metadata information is internal and created in the internal ConfigureMetadata override.
Describe the solution you'd like An API such as the above to determine and/or list the valid children of a given element.
Describe alternatives you've considered One way might be to add the child then validate it, but this seems the wrong approach.
@cwensley , Thanks for the suggestion. I've added the enhancement request label to your post. If you have time, pull requests are always appreciated.
Thanks for the quick reply @mikeebowen! Good to know you will accept changes. Do you have any preference of where/how this sort of functionality should be added? Perhaps something like:
class OpenXmlElement
{
public bool CanAddChild<T>() where T: OpenXmlElement;
public IEnumerable<Type> ValidChildren { get; }
}
or some form of extension methods? I'm not too intimately familiar with the APIs to know where best to put these.
Thanks!
Adding them to OpenXmlElement, seems reasonable to me. What do you think @twsouthwick & @tomjebo ?
Instead of using ChildElementInfoAttribute, use the internal element Metadata - it should expose the information you need.
One of the changes I'm working on (it's been a long time coming and should be turned on for the next release) is to move away from Type being used to identify elements, but rather the qualified name of an element. With that in mind, how about the following API:
class OpenXmlElement
{
public bool IsValidChild(OpenXmlElement element);
}
(you mentioned above an either/or for the exposed APIs, and I'd prefer to go with this)