First, JAXP DOM parsing javax.xml.parsers
1. Get the Document Object
Get the Instance factory *javax.xml.parsers.documentbuilderfactory
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Get analytic *javax.xml.parsers.documentbuilderfactory
Documentbuilder builder = Factory.newdocumentbuilder ();
Get document-Parse XML document Java.io.FileNotFoundException *org.w3c.dom.document
Document document = Builder.parse ("books.xml"); Refers to a file under the root path of a Java project
2. Get the content you need: get all the books
Get all the book elements
NodeList bookelements = document.getElementsByTagName ("book");
3. Traverse
* Get length
Bookelements.getlength ()
* Get the node that refers to the index
Bookelements.item (i);
* Obtained by element, the property specified by the current element
Element.getattribute ("id");
* Get the name of the current node
Node.getnodename ();
* Gets all the text of the child node of the current node
Node.gettextcontent ()
* For example:<book><title>java</title></book> and string "<title>Java</title>"
Second, save
Obtaining a Persisted object instance factory
Transformerfactory factory = Transformerfactory.newinstance ();
Getting persisted objects
Transformer Transformer = Factory.newtransformer ();
Save the memory data to the hard disk
Source: Document encapsulates document to source
Source Xmlsource = new Domsource (document);
Result: Books.jasp.xml "file path" is encapsulated into result
Result outputtarget = new Streamresult ("Books.jasp.xml");
Transformer.transform (Xmlsource, outputtarget);
Summary of Java XML (III.)--dom parsing