openxml

How to get retrieve only custom slide tags in OpenXML?


I was using the OpenXML library in C# and trying to get the user defined tags attached to a specific slide.

Here's how I initially went about it:

//  SlidePart slidePart;
var slideTags = slidePart.UserDefinedTagsParts.SelectMany(tp => tp.TagList.Elements<Tag>());

However, this does not only return the custom tags attached to the slide, but also all of the tags attached to the shapes inside the slide.

I eventually found a solution and will post an answer.


Solution

  • The trick is to make use of relationship IDs. (I'm used to Office Interop so OpenXML is such a headache)

    // Get the slide-specific tag relationship ID
    var slideSpecificTagsId = slidePart.Slide
                                       .Descendants<CustomerDataList>()
                                       .SingleOrDefault(cdl => cdl.Parent.GetType() == typeof(CommonSlideData))?
                                       .Descendants<CustomerDataTags>()
                                       .SingleOrDefault()
                                       .Id;
    
    // use that relationship ID to get to retrieve only that specific part
    var slideSpecificTags = slideSpecificTagsId != null
                            ? ((UserDefinedTagsPart)slidePart.GetPartById(slideSpecificTagsId))
                                                             .TagList
                                                             .Elements<Tag>()
                                                             .ToList()
                            : null;