DOM parsing (a)
using dom parsed xml document will all loaded into memory, and then converts all of the content node xml document (the object) on the tree.
Advantages:
random parse
can modify the file
you can create xml file
drawbacks:
for small files parsing, high memory requirements
1.1.1 xml respective output key information (using analytical dom)
package xml2; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class domTest { public static void main(String[] args) throws Exception { // 创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/xml2/desk.xml"); // List = document.getElementsByTagName a NodeList ( "Disk"); for (int I = 0; I <list.getLength (); I ++) { the Node Node = list.item (I); // two disk, by an index can be get any of Disk // Print properties section node node node name, and value, at the same time, there may be multiple attributes, so it is still a collection returned. System.out.println ( .. Node.getAttributes () Item (0) .getNodeName () + ":" + node.getAttributes () Item (0) .getNodeValue ()); a NodeList Node.getChildNodes List2 = (); // because the disk label have child nodes spaces, it has no child nodes, so I do not have to consider this, then, will be a first null pointer exception // solving the problem, then direct node was once sentenced segment type value is 1 (element node) for (int J = 0; J <list2.getLength (); J ++) { IF (list2.item (J) .getNodeType () ==. 1) { System.out.println (list2.item (J). getNodeName () + ":" + list2.item (j) .getTextContent ()); // Node attributes = node.getAttributes().item(0); // System.out.println(attributes); // System.out.println(attributes.getNodeName()); // System.out.println(attributes.getNodeType()); // System.out.println(attributes.getNodeValue()); } }
<?xml version="1.0" encoding="UTF-8"?> <disks> <disk name='c盘'> <size>10G</size> <directory>100</directory> <file>200</file> </disk> <disk name='d盘'> <size>20G</size> <directory>200</directory> <file>3000</file> </disk> </disks>