Jak projít DOM dokumentu OneNote v jazyce Python
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, přímá iterace a DocumentVisitor.
Model objektu dokumentu
DOM je striktní strom:
Document
├── Page
│ ├── Title
│ │ ├── TitleText (RichText)
│ │ ├── TitleDate (RichText)
│ │ └── TitleTime (RichText)
│ └── Outline
│ └── OutlineElement
│ ├── RichText
│ ├── Image
│ ├── AttachedFile
│ └── Table
│ └── TableRow
│ └── TableCell
│ └── RichText / Image
└── Page (next page ...)Každý uzel zdědí od Node. Vstupní uzly , které dědí děti CompositeNode.
Metod 1: GetChildNodes (rekurzivní, typově filtrované)
CompositeNode.GetChildNodes(Type) provádí rekurzivní hluboký vyhledávání celého podstromu a vrací plochý seznam všech uzlů odpovídajících danému typu. Je to nejpohodlnější přístup pro extrakci obsahu:
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)}")Rozsah vyhledávání na jedné stránce zavoláním GetChildNodes v roce Page místo: 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")Metoda 2: Přímá iterování dětí
for child in node iteruje okamžitý děti a CompositeNode.Použijte to , když potřebujete určitou úroveň hierarchie:
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__}")Metodou 3: DocumentVisitor
DocumentVisitor poskytuje vzor návštěvníka pro strukturované průcházky. Přehlížejte pouze VisitXxxStart/End Návštěvník je odeslán zavoláním na adresu: 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())Dostupné metody návštěvníků
| Metoda párů | Typ uzlu |
|---|---|
VisitDocumentStart/End | Document |
VisitPageStart/End | Page |
VisitTitleStart/End | Title |
VisitOutlineStart/End | Outline |
VisitOutlineElementStart/End | OutlineElement |
VisitRichTextStart/End | RichText |
VisitImageStart/End | Image |
Jak se vynořit na strom
Každý uzel je vystaven. ParentNode a a) Document vlastnost pro navádění směrem nahoru:
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__}")
breakMetody řízení dětí
CompositeNode také odhaluje in-memory child management (užitečné pro programovou konstrukci dokumentů, i když zpětné psaní na .one není podporováno):
| Metodika | Popis: |
|---|---|
node.FirstChild | První přímé dítě nebo None |
node.LastChild | Poslední přímé dítě nebo None |
node.AppendChildLast(child) | Přidat dítě na konec . |
node.AppendChildFirst(child) | Přidat dítě na začátku . |
node.InsertChild(index, child) | Vkládání v poloze |
node.RemoveChild(child) | Odveďte dítě. |
Počítání uzlů s návštěvou
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}")Jak vybrat správnou cestu?
| Příběh: | Nejlepší přístup |
|---|---|
| Zjistěte všechny uzly jednoho typu (např. všechny RichText) | GetChildNodes(RichText) |
| Iterované přímé děti (ne rekurzivní) | for child in node |
| Procházka stromem s kontextem (hloubka, mateřský stav) | DocumentVisitor |
| Navegujte od obsahu až k rodnému nebo kořenovému dokumentu. | node.ParentNode / node.Document |
Související zdroje: