This project has moved and is read-only. For the latest updates, please go here.

Issues with Ids

Jun 17, 2015 at 1:57 PM
Edited Jun 17, 2015 at 1:58 PM
In HelperFunctions.GetUniqueId only the body is scanned for already used ids, but not header and footer. Had a document which caused a problem because of this. I extended the GetUniqueId function like this:

internal static int GetUniqueId(DocX doc) {
          int newDocPrId = 1;
          List<string> existingIds = new List<string>();
          GetUniquieId(doc.Xml, existingIds);
          if (doc.Headers != null) {
              if (doc.Headers.first != null) GetUniquieId(doc.Headers.first.Xml, existingIds);
              if (doc.Headers.even != null) GetUniquieId(doc.Headers.even.Xml, existingIds);
              if (doc.Headers.odd != null) GetUniquieId(doc.Headers.odd.Xml, existingIds);
          }
          if (doc.Footers != null) {
              if (doc.Footers.first != null) GetUniquieId(doc.Footers.first.Xml, existingIds);
              if (doc.Footers.even != null) GetUniquieId(doc.Footers.even.Xml, existingIds);
              if (doc.Footers.odd != null) GetUniquieId(doc.Footers.odd.Xml, existingIds);
          }

          while (existingIds.Contains(newDocPrId.ToString()))
              newDocPrId++;

          return newDocPrId;
      }
and

private static void GetUniquieId(XElement Xml, List<string> existingIds) {
          foreach (var docPrId in Xml.Descendants(XName.Get("docPr", DocX.wp.NamespaceName))) {
              existingIds.Add(docPrId.Attributes().FirstOrDefault(x => x.Name == "id").Value);
          }

          foreach (var docPrId in Xml.Descendants(XName.Get("abstractNumId", DocX.w.NamespaceName))) {
              existingIds.Add(docPrId.Attributes().FirstOrDefault(x => x.Name == "id").Value);
          }

          foreach (var bookmarkId in Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName))) {
              var idAtt = bookmarkId.Attributes().FirstOrDefault(x => x.Name.LocalName == "id");
              if (idAtt != null)
                  existingIds.Add(idAtt.Value);
          }

          foreach (var bookmarkId in Xml.Descendants(XName.Get("bookmarkEnd", DocX.w.NamespaceName))) {
              var idAtt = bookmarkId.Attributes().FirstOrDefault(x => x.Name.LocalName == "id");
              if (idAtt != null)
                  existingIds.Add(idAtt.Value);
          }
      }
Every function calling the GetUniqueId function has to be adopted to the new parameter. Please have a look at it.