Search code examples
c#openxml

Open xml cannot get a drawing element


I am going through a docx, uscing open xml to find some images.

So, I am doing this to get all the Drawings, that got a docProperties as child, with a title containing

List<Drawing> sdtElementDrawing = wordDoc.MainDocumentPart.Document.Descendants<Drawing>()
                                              .Where(element =>
                                                  element.GetFirstChild<Drawing>() != null
                                                  && element.GetFirstChild<DocProperties>().Title.Value.Contains("IMAGE")).ToList();

And the docx as xml looks likes this in the first part(it is normally bigger, but I only copy the relevant part) :

<w:drawing>
      <wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="251658240" behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
        <wp:simplePos x="0" y="0" />
        <wp:positionH relativeFrom="column">
          <wp:posOffset>2171700</wp:posOffset>
        </wp:positionH>
        <wp:positionV relativeFrom="paragraph">
          <wp:posOffset>-1168400</wp:posOffset>
        </wp:positionV>
        <wp:extent cx="2286000" cy="746760" />
        <wp:effectExtent l="0" t="0" r="0" b="0" />
        <wp:wrapNone />
        <wp:docPr id="1" name="Image 1" descr="C:\Users\Pictures\IMAGERM.jpg" title="IMAGERM" />     
 </wp:anchor>
    </w:drawing>

But I don't find sdtElementDrawing.

So I think I miswrote the sdtElementDrawing query. I must miss an obvious way to tell "get the drawing child, where there is a DocProperties with the title like IMAGE", but I cannot find it.

I also tried this, but doesn't work better :

                        List<Drawing> sdtElementDrawing = wordDoc.MainDocumentPart.Document.Descendants<Drawing>()
                                      .Where(element =>
                                          element.GetFirstChild<Drawing>() != null && 
                                          element.GetFirstChild<Drawing>().Anchor.GetFirstChild<DocProperties>().Title.Value.Contains("IMAGE")).ToList();

Solution

  • Have you tried this one?

    List<Drawing> sdtElementDrawing = wordDoc.MainDocumentPart.Document.Descendants<Drawing>()
        .Where(element => element.Descendants<DocProperties>().Any(
            prop => prop.Title.Value.ToUpper().Contains("IMAGE")
        )).ToList();