Search code examples
c#.netpowerpointopenxmlopenxml-sdk

Open XML SDK: How to retrieve parent OpenXmlPart from a TypedOpenXmlCompositeElement?


Is it possible to retrieve the parent DocumentFormat.OpenXml.Packaging.OpenXmlPart instance for a DocumentFormat.OpenXml.Presentation.TypedOpenXmlCompositeElement?

For instance, in the code below, I want to obtain the SlidePart (a derived class of OpenXmlPart) instance for the Shape (a derived class of TypedOpenXmlCompositeElement):

using P = DocumentFormat.OpenXml.Presentation;

public static void GetSlidePart()
{
    var presDoc = PresentationDocument.Open("test.pptx", false);
    P.Shape pShape = presDoc.PresentationPart!.SlideParts.First().Slide.CommonSlideData!.ShapeTree!.Elements<P.Shape>().First();
    //...
    
    SlidePart parentSlidePartOfPShape = // pShape...
}

Solution

  • @adam-shakhabov I've made a change in the OpenXmlPartRootElement class that allows access to the OpenXmlPart property. With this change, the following code should work for what you're trying to do:

    OpenXmlPartRootElement partRoot = pShape.Ancestors<OpenXmlPartRootElement>().First();
    
    if (partRoot.OpenXmlPart is null)
    {
        Console.WriteLine("partRoot is null");
        return;
    }
    
    OpenXmlPart part = partRoot.OpenXmlPart;
    

    I mentioned you in the PR on github which has already been merged into main and will be in v3.0. Let me know if you have any questions or follow-up on this.