Summary of Java XML (III.)--dom parsing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.