Search code examples
c#openxmldocx

C# code to access author name in DOCX returning error on GetXDocument. 'does not contain a definition for 'GetXDocument'


I am trying to debug C# code to access the 'author' attribute in DOCX files. The method below is being passed a variable 'savePath' which represents the DOCX file. VS doesn't like GetXDocument and returns the error:

DocumentFormat.OpenXml.Packaging.MainDocumentPart does not contain a definition for GetXDocument and no extension method GetXDocument.

What am I doing wrong here?

    private void changeRevAuthor(string savePath)
    { 
        List<string> result = new List<string>();
        XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
        WordprocessingDocument wordDocument = WordprocessingDocument.Open(savePath, false);

        XDocument mainDocumentXDoc = wordDocument.MainDocumentPart.GetXDocument();

        var nodes = mainDocumentXDoc.Descendants().Where(x => x.Attributes(w + "author").Count() > 0).ToList();
        foreach (var node in nodes)
        {
            string authorname = node.Attribute(w + "author").Value;
            if (!result.Contains(authorname))
                result.Add(authorname);
        }
        wordDocument.Package.Close();
        return result;

    }

Solution

  • GetXDocument is part of OpenXML Powertools libary. Nuget it and add it to your solution and you will be good.

    Once you add the OpenXmlPowerTools package from nuget - import the following namespace

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using OpenXmlPowerTools;