2016-07-27 81 views
0

我需要通过OpenXML将某些内容添加到Word文档中。我使用了Open Xml生产力工具来生成代码,我试图调整它,以便它可以重用于所有文档。生成OpenXML DocProperties Id

显然需要一个DocProperties对象,它需要一个唯一的Id。有没有办法自动生成这些ID?或者,我是否需要执行类似下面的代码来查找使用的最大ID并从那里增加?

有没有更好的方法?这看起来很昂贵。我使用.NET中的C#从Microsoft的Open XML SDK(v2.5)中使用DocumentFormat.OpenXml。

static uint getMaxDocPropertyId(WordprocessingDocument doc) 
    { 
     return doc 
      .MainDocumentPart 
      .Parts 
      .Select(x => x.OpenXmlPart.RootElement) 
      .Where(x => x != null) 
      .SelectMany(x => x.Descendants<Wp.DocProperties>()) 
      .Max(x => x.Id.Value as uint?) ?? 0; 
    } 

回答

0

这对我很有效,但它本质上是做同样的事情。对我而言,我不认为这是可以避免的,因为我所寻找的DocProperties属于图像,并且我的文档中有多个文档,因此每个文档都埋在段落的深处 - >运行 - >绘图 - >和Inline的孩子。

private uint GetMaxDocPropertyId(WordprocessingDocument doc) 
{ 
    return doc 
     .MainDocumentPart 
     .RootElement 
     .Descendants<DocProperties>() 
     .Max(x => (uint?) x.Id) ?? 0; 
}