遍歷 FlowDocument

小林野夫發表於2024-04-26

我們經常要遍歷FlowDocument文件 查詢元素,具體的寫法之一 :

列印出文件的結構

  private void TransformImagesTo642(FlowDocument flowDocument)
  {
      TextPointer navigator = flowDocument.ContentStart;
      while (navigator.CompareTo(flowDocument.ContentEnd) < 0)
      {
          switch (navigator.GetPointerContext(LogicalDirection.Forward))
          {
              case TextPointerContext.ElementStart:
                  // Output opening tag of a TextElement
               Debug.WriteLine("<{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                  break;
              case TextPointerContext.ElementEnd:
                  // Output closing tag of a TextElement
                  Debug.WriteLine("</{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                  break;
              case TextPointerContext.EmbeddedElement:
                  // Output simple tag for embedded element
                  Debug.WriteLine("<{0}/>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                  break;
              case TextPointerContext.Text:
                  // Output the text content of this text run
                  Debug.WriteLine(navigator.GetTextInRun(LogicalDirection.Forward));
                  break;
          }

          // Advance the naviagtor to the next context position.
          navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
      } // End while.

  }

相關文章