Novacode.DocX.GetHeaderOrFooterByType C# (CSharp) Method

GetHeaderOrFooterByType() private method

private GetHeaderOrFooterByType ( string type, bool isHeader ) : object
type string
isHeader bool
return object
        private object GetHeaderOrFooterByType(string type, bool isHeader)
        {
            // Switch which handles either case Header\Footer, this just cuts down on code duplication.
            string reference = "footerReference";
            if (isHeader)
                reference = "headerReference";

            // Get the Id of the [default, even or first] [Header or Footer]

            string Id =
            (
                from e in mainDoc.Descendants(XName.Get("body", w.NamespaceName)).Descendants()
                where (e.Name.LocalName == reference) && (e.Attribute(w + "type").Value == type)
                select e.Attribute(r + "id").Value
            ).LastOrDefault();

            if (Id != null)
            {
                // Get the Xml file for this Header or Footer.
                Uri partUri = mainPart.GetRelationship(Id).TargetUri;

                // Weird problem with PackaePart API.
                if (!partUri.OriginalString.StartsWith("/word/"))
                    partUri = new Uri("/word/" + partUri.OriginalString, UriKind.Relative);

                // Get the Part and open a stream to get the Xml file.
                PackagePart part = package.GetPart(partUri);

                using (TextReader tr = new StreamReader(part.GetStream()))
                {
                    var doc = XDocument.Load(tr);

                    // Header and Footer extend Container.
                    Container c;
                    if (isHeader)
                        c = new Header(this, doc.Element(w + "hdr"), part);
                    else
                        c = new Footer(this, doc.Element(w + "ftr"), part);

                    return c;
                }
            }

            // If we got this far something went wrong.
            return null;
        }