使用 DOM

Overview

DOM 层将一个 HTML 页面建模为一个类型化节点的树。Document 是入口点和节点工厂;Element 和 Node 负责 API 的操作和遍历。


创建节点

Document.create_element()、create_text_node()、create_comment() 和 create_document_fragment() 生成节点;append_child() 将它们附加:

from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
doc.append_child(el)

Attributes

Element.set_attribute()、get_attribute()、has_attribute() 和 remove_attribute() 管理标记属性;Attr 和 NamedNodeMap 将它们以对象形式公开:

from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")
doc.append_child(el)

树操作

Node 提供结构工具箱:insert_before()、remove_child()、replace_child()、clone_node() 和 contains(),以及 child_nodes、parent_node、first_child 访问器和用于子树文本的 text_content。get_root_node() 和 has_child_nodes() 直接回答结构性问题。

查找与遍历

Document.get_element_by_id() 按 id 检索元素。NodeList 和 HTMLCollection 保存结果集;NodeIterator 与 TreeWalker(使用 NodeFilter)按文档顺序遍历子树。

观察变更

MutationObserver 将树的更改记录为 MutationRecord 条目,映射标准观察者模式以响应结构编辑。


技巧与最佳实践

  • 通过所属的 Document 创建每个节点——节点的作用域是文档级别;使用 Document.import_node() 或 adopt_node() 将它们在文档之间移动
  • 在处理整棵子树文本时,优先使用 text_content 而不是手动的 Text 节点操作
  • 使用 DocumentFragment 在单个 append_child() 之前组装节点批次
  • 在 get_attribute() 之前检查 has_attribute(),当缺失属性具有意义时

常见问题

问题原因解决方案
节点出现在错误的文档中节点由不同的 Document 创建先使用 import_node() 或 adopt_node() 移动它
属性查找未返回任何内容属性从未在元素上设置使用 has_attribute() 进行防护
子树文本为空在子节点附加之前读取 text_content先附加子节点,然后读取

FAQ

哪个类创建新元素?

Document — 其 create_element() 方法是元素的工厂,同时还有用于文本、注释和片段的兄弟工厂。

如何在两个文档之间移动子树?

使用 Document.import_node() 进行复制,或使用 adopt_node() 进行转移,然后使用 append_child() 附加。

是否存在用于树更改的观察者 API?

是的 — MutationObserver 提供描述结构和属性更改的 MutationRecord 批次。


API Reference 摘要

类/方法描述
Document.create_element创建元素节点
Document.get_element_by_id按 id 查找元素
Element.set_attribute设置标记属性
Node.insert_before在参考子节点前插入节点
Node.clone_node复制节点或子树
MutationObserver观察树的变更
TreeWalker过滤后的文档顺序遍历

另请参阅

 中文