1. DOM parser
1) First get the factory instance of the DOM parser
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
2) Get the DOM parser from the DOM factory
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
3) Convert the XML document to be parsed into an input stream so that the DOM parser can parse it
InputStream is= new FileInputStream("test1.xml");
4) Parse the input stream of the XML document and get a Document
Document doc=dombuilder.parse(is);
5) Get the root node of the XML document
Element root=doc.getDocumentElement();
6) Get the child nodes of the node
NodeList books=root.getChildNodes();
2. Transformer converter
Use Transformer to output the updated XML document
transformDomToXml(Document document,String FileName){
try{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(FileName));
transformer.transform(source,result);
}catch (TransformerConfigurationException tce) {
System.out.println(" " + tce.getMessage() );
}catch (TransformerException te) {
System.out.println(" " + te.getMessage() );
}
DOM is an interface for javascript to operate web pages, and it is called the Document Object Model in full. Its function is to convert the webpage into a javascript object, so that various operations (such as adding or deleting content) can be performed on the webpage using javascript. The browser will parse the HTML document into a series of nodes according to the DOM model, and then form a tree structure from these nodes. The smallest unit of DOM is called a node, and the tree structure of a document (DOM tree) consists of 12 types of nodes. This article will mainly explain the DOM node type
In general, nodes have at least three basic properties: nodeType, nodeName and nodeValue. Different node types have different values for these three attributes
The nodeType property returns a constant value for the node type. Different types correspond to different constant values, and 12 types correspond to constant values from 1 to 12 respectively
Element Node Node.ELEMENT_NODE(1)
Attribute Node Node.ATTRIBUTE_NODE(2)
Text node Node.TEXT_NODE(3)
CDATA point Node.CDATA_SECTION_NODE (4)
Entity reference name node Node.ENTRY_REFERENCE_NODE(5)
Entity name node Node.ENTITY_NODE(6)
Process instruction node Node.PROCESSING_INSTRUCTION_NODE(7)
Comment Node Node.COMMENT_NODE(8)
Document Node Node.DOCUMENT_NODE(9)
Document type node Node.DOCUMENT_TYPE_NODE(10)
Document Fragment Node Node.DOCUMENT_FRAGMENT_NODE(11)
DTD declaration node Node.NOTATION_NODE(12)