Package Jiexi;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Org.w3c.dom.document;import Org.w3c.dom.node;import Org.w3c.dom.nodelist;//jaxp Dom method parsing XML document instance public class JaxpCRUD {public static void main (string[] args) throws Exception {//1, get parser documentbuilderdocumentbuilderfactory dbf= Documentbuilderfactory.newinstance ();D ocumentbuilder db=dbf.newdocumentbuilder ();// 2, obtain Document object representing the entire XML document Document=db.parse ("Src/book.xml"); test1 (document);} 1, get the content of the concrete node public static void Test1 (document document) {//Get the price of the second book NodeList List=document.getelementsbytagname ("Price "); int length=list.getlength ();//Get the number of ELEMENT nodes System.out.println (length); Node Node=list.item (1);//corner Mark starting from 0 System.out.println (node.gettextcontent ());} 2. Traverse all element nodes public static void Test2 (node node) {//1, determine if node is an element node, if yes, print the node if (Node.getnodetype () ==node.element_ node) {//determine if the element node is System.out.println (Node.getnodename ());} 2, determine if there is a child node nodelist children=node.getchildnodes (); for (int i=0;i<chIldren.getlength (); i++) {node N=children.item (i); Test2 (n);//3, recursively invokes}}//3, modifies the subject content of an element node//4, adds child elements to the specified element node//5, Adds a sibling element node//6 to the specified element node, deletes the specified element node//7, and operates an XML file property}
Java Operation XML