打开XML word文档-查找高亮显示的文本



我有一个word文档,其中每个段落都是很长的一行。比如:

"NameOfSomeSort     ----ASDdASFA---F-TEXT-FASFASFAS----FASFASF"
字符

"TEXT"

被高亮显示。我需要能够分辨出行中哪些字符被高亮显示,并获得它们在行的位置索引。

我能够通过Interoop做到这一点,但操作将花费cc5 -10小时来浏览整个文档。所以我尝试了OpenXML,但是当我循环使用段落文本时,我无法获得像Highlight这样的文本属性。

高亮应用于运行(在runProperties中)(https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.highlight (v = office.14) . aspx)

如果你的文本是"aaaaa [i am highlight] bbbb",openxml将看起来像

<w:Paragraph>
  <w:Run><w:Text>aaaaa</w:Text></w:Run>
  <w:Run>
    <w:rPr>
      <w:highlight w:val="yellow" />
    </w:rPr>
    <w:Text>[i am highlight]</w:Text>
  </w:Run>
  <w:Run><w:Text>bbbb</w:Text></w:Run>  
</w:Paragraph>

所以,要找到哪个文本是高亮的,你必须搜索高亮标签比如Paragraph.Descendants<Highlight>()

如果你需要检索位置,你可以使用一些算法,如

// Suppose you have the paragraph p you want to inspec and the run r containing highlight
int pos = 0;
OpenXmlElement oxe = null;
// From the run search for the parent (Paragraph p)
// Add the length of previous text in pos
while ((oxe = r.previousSibling()) != p)
{
  pos += ((Run)oxe).Innertext.Length;
}
// here pos should return where the highlight begin (maybe it's pos+1...)

最新更新