DOM解析核心类库

温馨提示

关注我的公众号【Java剑主】,学习更多有深度的技术文章。本博客不在记录原创博文,请移步公众号获取最新内容。

修道注重根基,熟透原理方能看透事物本质,编程亦如此! Java修炼之道,道心坚不移!踏剑寻梦,不忘初心!

DOM解析核心类库

Java对DOM的支持
DOM属于W3C制定的标准,而在Java中也完整的支持了DOM解析的操作,如果要想清楚的知道DOM
的解析操作则需要查询JDK文档取得。(都保存在org.w3c.dom包中)
1.文档解析工厂类:javax.xml.parsers.DocumentBuilderFactory
本类的构造方法使用了protected权限声明所以属于构造封装;
取得DocumentBuilderFactory类的实例化对象:
public static DocumentBuilderFactory newInstance()
取得DocumentBuilder类对象:
public abstract DocumentBuilder newDocumentBuilder()throws ParserConfigurationException

2.文档解析类:javax.xml.parsers.DocumentBuilder;
创建一个新的文档:public abstract Document newDocument()
解析已有的文件:
public Document parse?(File f)throws SAXException,IOException
从输入流解析内容:
public Document parse?(InputStream is)throws SAXException,IOException
以上不管是创建新的还是解析已有的都会返回一个org.w3c.dom.Document接口对象;
所以现在能否进行DOM树的操作关键在于Document接口的操作上,
*.xml文件在程序中就使用Document来描述 图一

DOM解析核心类库

3.如何操作DOM树呢? 图二

DOM解析核心类库
DOM操作的核心在于Document接口。但是在整个DOM树上所有的元素都是通过Node来完成的。
在Node接口下有几个常见的子接口:Element,Attr,Text

图三

DOM解析核心类库
观察Document接口定义:public interface Document extends Node ;
创建属性:public Attr createAttribute(String name)throws DOMException;
创建元素:public Element createElement(String tagName)throws DOMException;
创建文本:public Text createTextNode(String data);

图四

DOM解析核心类库
取得指定名称的元素:public NodeList getElementsByTagName(String tagname);
此时的方法返回一个NodeList接口对象,包含的是多个Node接口对象,里面有如下方法:
取得节点个数:public int getLength()
取得指定的索引对象:public Node item(int index);


观察Node接口:是所有操作的父接口,方法如下:
追加子节点:public Node appendChild(Node newChild) throws DOMException
取得一个节点中的所有子节点:public NodeList getChildNodes()
取得第一个子节点:public Node getFirstChild();
取得最后一个子节点:public Node getLastChild();
取得节点名字:public String getNodeName();
取得节点类型:public short getNodeType();
取得节点内容:public String getNodeValue()throws DOMException;
取得父节点:public Node getParentNode();
是否有子节点:public boolean hasChildNodes();
删除子节点:public Node removeChild(Node oldChild)throws DOMException;
替换节点:public Node replaceChild(Node newChild,Node oldChild)throws DOMException;
设置节点内容:public void setNodeValue(String nodeValue)throws DOMException;


观察Element子接口的方法
取得元素中指定属性的内容:public String getAttribute(String name)
取得元素中接口对象:public AttributeNode(String name)
查询当前元素下的指定元素的名称全部对象:public NodeList getElementsByTagName(String name)
取得标签名称:public String getTagName()
判断指定的属性是否存在:public boolean hasAttribute(String name)
删除属性:public void removeAttribute(String name)throws DOMException
删除Attr内容:public Attr removeAttributeNode(Attr oldAttr)throws DOMException
设置属性内容:public void setAttribute(String name,String value)throws DOMException


观察Attr子接口方法:
取得属性内容:public String getValue()
取得属性名字:public String getName()
设置属性内容:public void setValue(String value)throws DOMException