打开XML电动工具识别段落索引

时间:2016-08-04 15:28:26

标签: c# openxml

我遇到了将复杂文档与特定位置的标题合并的问题。

以下是一个例子:

var letterhead = @"C:\Users\dheale\Desktop\Word Docs\TESTING\StandardLetterhead.DOCX";
var blackrule = @"C:\Users\dheale\Desktop\Word Docs\TESTING\NJBlackrule.DOCX";
var asb = @"C:\Users\dheale\Desktop\Word Docs\TESTING\asb.DOCX";
var outDoc = @"C:\Users\dheale\Desktop\Word Docs\TESTING\out.DOCX";

var sources = new List<Source>
{
    new Source(new WmlDocument(asb), 0, 80, false),
    new Source(new WmlDocument(letterhead), true),
    new Source(new WmlDocument(asb), 80,120, false),
    new Source(new WmlDocument(blackrule), true),
    new Source(new WmlDocument(asb), 200, false),
    new Source(new WmlDocument(letterhead), true)
};

var doc = DocumentBuilder.BuildDocument(sources);

我的问题是试图找出段落索引是什么。原始文档具有标记以标识模板的放置位置。

目前要获取ID,我正在执行以下操作:

var ParagraphIndex = wordDoc.MainDocumentPart.Document.Body.ChildElements
    .Where(w => w.XmlQualifiedName.Name == "p").ToList()
    .FindIndex(f => f.InnerXml.Contains(templateTag));

但是,文档越长,该索引就越多。

是否有更好,更准确的方法来获取段落的索引?

1 个答案:

答案 0 :(得分:0)

为什么不使用标记获取Paragraph,然后在其后插入您的内容?

var searchedParagraph = wordDoc.MainDocumentPart.Document.Body.ChildElements
    .Where(w => w.XmlQualifiedName.Name == "p")
    .FirstOrDefault(f => f.InnerXml.Contains(templateTag));
if (searchedParagraph != null) {
   OpenXmlElement parent = searchedParagraph.Parent;
   //Add Code here to create your paragraphWithContent
   ....
   //End paragraphWithContent 

   parent.InsertAfter(paragraphWithContent, searchedParagraph);
}

像这样。