如何在 Python 中遍历 OneNote 文档 DOM

如何在 Python 中遍历 OneNote 文档 DOM

Aspose.Note FOSS for Python represents a OneNote section file as a tree of typed Python objects. Understanding how to traverse this tree efficiently is the foundation for all content extraction tasks. This guide covers all three traversal approaches: GetChildNodes, 直接迭代,和 DocumentVisitor.


文档对象模型

OneNote DOM 是一棵严格的树::

Document
  ├── Page
  │     ├── Title
  │     │     ├── TitleText (RichText)
  │     │     ├── TitleDate (RichText)
  │     │     └── TitleTime (RichText)
  │     └── Outline
  │           └── OutlineElement
  │                 ├── RichText
  │                 ├── Image
  │                 ├── AttachedFile
  │                 └── Table
  │                       └── TableRow
  │                             └── TableCell
  │                                   └── RichText / Image
  └── Page  (next page ...)

每个节点继承自 Node.。拥有子节点的节点继承自 CompositeNode.


方法 1:GetChildNodes(递归、类型过滤)

CompositeNode.GetChildNodes(Type) 对整个子树执行递归的深度优先搜索,并返回所有匹配给定类型的节点的扁平列表。这是内容提取最方便的方法::

from aspose.note import Document, RichText, Image, Table, AttachedFile

doc = Document("MyNotes.one")

##All RichText nodes anywhere in the document
texts = doc.GetChildNodes(RichText)
print(f"RichText nodes: {len(texts)}")

##All images
images = doc.GetChildNodes(Image)
print(f"Image nodes: {len(images)}")

##All tables
tables = doc.GetChildNodes(Table)
print(f"Table nodes: {len(tables)}")

##All attachments
attachments = doc.GetChildNodes(AttachedFile)
print(f"AttachedFile nodes: {len(attachments)}")

通过调用,将搜索范围限定在单个页面上 GetChildNodesPage 而不是 Document:

from aspose.note import Document, Page, RichText

doc = Document("MyNotes.one")
for page in doc.GetChildNodes(Page):
    page_texts = page.GetChildNodes(RichText)
    print(f"  Page has {len(page_texts)} text nodes")

方法 2:直接子节点迭代

for child in node 遍历 直接的 子节点的 CompositeNode.。当您只需要层级中的特定一级时使用::

from aspose.note import Document

doc = Document("MyNotes.one")

##Direct children of Document are Pages
for page in doc:
    title = (
        page.Title.TitleText.Text
        if page.Title and page.Title.TitleText
        else "(untitled)"
    )
    print(f"Page: {title}")
    # Direct children of Page are Outlines (and optionally Title)
    for child in page:
        print(f"  {type(child).__name__}")

方法 3:DocumentVisitor

DocumentVisitor 提供一种用于结构化遍历的访问者模式。仅覆盖 VisitXxxStart/End 您需要的方法。通过调用来分发访问者 doc.Accept(visitor):

from aspose.note import (
    Document, DocumentVisitor, Page, Title,
    Outline, OutlineElement, RichText, Image,
)

class StructurePrinter(DocumentVisitor):
    def __init__(self):
        self._depth = 0

    def _indent(self):
        return "  " * self._depth

    def VisitPageStart(self, page: Page) -> None:
        t = page.Title.TitleText.Text if page.Title and page.Title.TitleText else "(untitled)"
        print(f"{self._indent()}Page: {t!r}")
        self._depth += 1

    def VisitPageEnd(self, page: Page) -> None:
        self._depth -= 1

    def VisitOutlineStart(self, outline) -> None:
        self._depth += 1

    def VisitOutlineEnd(self, outline) -> None:
        self._depth -= 1

    def VisitRichTextStart(self, rt: RichText) -> None:
        if rt.Text.strip():
            print(f"{self._indent()}Text: {rt.Text.strip()!r}")

    def VisitImageStart(self, img: Image) -> None:
        print(f"{self._indent()}Image: {img.FileName!r} ({img.Width}x{img.Height}pts)")

doc = Document("MyNotes.one")
doc.Accept(StructurePrinter())

可用的访问者方法

方法对节点类型
VisitDocumentStart/EndDocument
VisitPageStart/EndPage
VisitTitleStart/EndTitle
VisitOutlineStart/EndOutline
VisitOutlineElementStart/EndOutlineElement
VisitRichTextStart/EndRichText
VisitImageStart/EndImage

向上导航树结构

每个节点公开 ParentNode 以及一个 Document 属性用于向上导航::

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    parent = rt.ParentNode   # OutlineElement, TableCell, Title, etc.
    root = rt.Document       # always the Document root
    print(f"  '{rt.Text.strip()!r}' parent={type(parent).__name__}")
    break

子节点管理方法

CompositeNode 还公开了内存中的子节点管理(对于程序化文档构建很有用,尽管不支持写回至 .one 不受支持)::

方法描述
node.FirstChild第一个直接子节点或 None
node.LastChild最后一个直接子节点或 None
node.AppendChildLast(child)在末尾添加子节点
node.AppendChildFirst(child)在开头添加子节点
node.InsertChild(index, child)在位置插入
node.RemoveChild(child)移除子节点

使用访问者计数节点

from aspose.note import Document, DocumentVisitor, Page, RichText, Image

class Counter(DocumentVisitor):
    def __init__(self):
        self.pages = self.texts = self.images = 0

    def VisitPageStart(self, page: Page) -> None:
        self.pages += 1

    def VisitRichTextStart(self, rt: RichText) -> None:
        self.texts += 1

    def VisitImageStart(self, img: Image) -> None:
        self.images += 1

doc = Document("MyNotes.one")
c = Counter()
doc.Accept(c)
print(f"Pages={c.pages}  RichText={c.texts}  Images={c.images}")

选择合适的遍历方法

场景最佳方案
查找所有特定类型的节点(例如所有 RichText)GetChildNodes(RichText)
仅遍历直接子节点for child in node
在上下文中遍历树(深度、父节点状态)DocumentVisitor
从内容向上导航到父节点或根节点node.ParentNode / node.Document

相关资源::

 中文