首先有必要了解一下什么是 DOM ? 下面是DOM 的官方定义
文档对象模型(DOM ) 是一个使程序和脚本有能力动态地访问和更新文档的内容、结构以及样式的
平台和语言中立的接口。
W3C DOM 被分为 3 个不同的部分/级别:
(1) 核心 DOM : 用于任何结构化文档的标准模型
(2) XML DOM : 用于 XML 文档的标准模型, 定义了所有 XML 元素的对象和属性 ,以及访问它
们 的方法(接口),换句话说,XML DOM 是用于获取、更改、添加或删除 XML 元素的标准。
(3) HTML DOM : 用于 HTML 文档的标准模型,定义了所有 HTML 元素的对象和属性,以及访问
它们的方法(接口)。
DOM 定义了所有文档元素的对象和属性,以及访问它们的方法(接口)。
下面主要介绍XML DOM 的相关内容 及其 解析方法(JAVA 实现)。
XML文档中每个成分都是一个节点(Node) 。包括文本节点(Text),属性节点(Attr),注释节
点(Comment),元素节点(Element),CDATASection节点,文档节点(Document),文档片段节
点(DocumentFragment),文档类型节点(DocumentType),实体节点(EntityType),实体引用节
点(EntityReference),Notation节点,处理指令节点(
ProcessingInstruction
)。
JAVA 中DOM 节点的类层次示意图如下。
org.w3c.dom .Node
- org.w3c.dom .Attr
- org.w3c.dom .CharacterData
- org.w3c.dom .Comment
- org.w3c.dom .Text
- org.w3c.dom .CDATASection
- org.w3c.dom .Document
- org.w3c.dom .DocumentFragment
- org.w3c.dom .DocumentType
- org.w3c.dom .Element
- org.w3c.dom .Entity
- org.w3c.dom .EntityReference
- org.w3c.dom .Notation
- org.w3c.dom .ProcessingInstruction
每个节点都有三个属性nodeName ,nodeValue 和 attributes 。各种节点的相应属性值如下所示。
Interface | nodeName | nodeValue | attributes |
---|---|---|---|
Attr | 与 Attr.name 相同 | 与 Attr.value 相同 | null |
CDATASection | "#cdata-section" | 与 CharacterData.data 相同,CDATA 节的内容 | null |
Comment | "#comment" | 与 CharacterData.data 相同,该注释的内容 | null |
Document | "#document" | null | null |
DocumentFragment | "#document-fragment" | null | null |
DocumentType | 与 DocumentType.name 相同 | null | null |
Element | 与 Element.tagName 相同 | null | NamedNodeMap |
Entity | entity name | null | null |
EntityReference | 引用的实体名称 | null | null |
Notation | notation name | null | null |
ProcessingInstruction | 与 ProcessingInstruction.target 相同 | 与 ProcessingInstruction.data 相同 | null |
Text | "#text" | 与 CharacterData.data 相同,该文本节点的内容 | null |