Experience 5--xml Programming (CRUD)--dom, sax parsing case Analysis __ Programming

Source: Internet
Author: User

One: DOM parsing XML documents, using DOM parsing method to check the XML document deletion, the technology to read all the XML documents exist in memory and then parse, slow, and when the memory is too large, will make memory overflow, system crashes

Packagecom.dom;

Importjava.io.FileOutputStream;

Importjava.io.IOException;

Importjavax.xml.parsers.DocumentBuilder;

Importjavax.xml.parsers.DocumentBuilderFactory;

Importjavax.xml.parsers.ParserConfigurationException;

Importjavax.xml.transform.Transformer;

Importjavax.xml.transform.TransformerException;

Importjavax.xml.transform.TransformerFactory;

Importjavax.xml.transform.dom.DOMSource;

Importjavax.xml.transform.stream.StreamResult;

Importorg.junit.Test;

Importorg.w3c.dom.Document;

Importorg.w3c.dom.Element;

Importorg.w3c.dom.Node;

Importorg.w3c.dom.NodeList;

Importorg.xml.sax.SAXException;

Publicclass Demo2 {

@Test

Get all nodes

public void ReadAll () throwsparserconfigurationexception, Saxexception, ioexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

Node Root =document.getelementsbytagname ("bookstore"). Item (0);

List (root);

}

Traversing elements

private void List (node node) {

if (node instanceof Element) {

System.out.println (Node.getnodename ());

}

NodeList list = Node.getchildnodes ();

for (int i=0;i<list.getlength (); i++) {

List (List.item (i));

}

}

@Test

Reading the value of a property

public void Readattribute () throwsparserconfigurationexception, Saxexception, ioexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

element element = (Element) document.getelementsbytagname ("BookName"). Item (0);//Here must remember not to forget to write the item () method, The method is to get the first few bookname nodes

System.out.println (Element.getattribute ("id"));

}

@Test

Add node (append)

public void Insert () throwsparserconfigurationexception, Saxexception, IOException, transformerexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db = Factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

Creating nodes

Element create = (Element) document.createelement ("Publishing house");

Create.settextcontent ("River Soft Publishing house");

Get the node to append to

element element = (Element) document.getelementsbytagname ("book"). Item (0);

Element.appendchild (create); Element can be added outside the root node. The contents must be added to the root of the time.

To add content from document documents to an XML file

Transformerfactory TFF =transformerfactory.newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (new Domsource (document), Newstreamresult (New FileOutputStream ("Src/book.xml"));

}

@Test

Add node at specified location

public void Insert1 () throwsparserconfigurationexception, Saxexception, IOException, transformerexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

Get reference node

element element = (Element) document.getelementsbytagname ("Price"). Item (1);

Creating node elements

Element creater = (Element) document.createelement ("Publishing house");

Creater.settextcontent ("River Soft Publishing house");

Get the node to append to

Element e = (Element) document.getelementsbytagname ("book"). Item (1);

E.insertbefore (creater, Element);

To add content from document documents to an XML file

Transformerfactory TFF =transformerfactory.newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (new Domsource (document), Newstreamresult (New FileOutputStream ("Src/book.xml"));

}

@Test

Delete an element node

public void Delete () throwsparserconfigurationexception, Saxexception, IOException, transformerexception{

Documentbuilderfactoryfactory = Documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

element element = (Element) document.getElementsByTagName ("Publishing House"). Item (1);

Get parent Node

Element e = (Element) document.getelementsbytagname ("book"). Item (1);

E.removechild (Element); Only child nodes can be removed cannot remove themselves

To add content from document documents to an XML file

Transformerfactory TFF =transformerfactory.newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (new Domsource (document), Newstreamresult (New FileOutputStream ("Src/book.xml"));

}

@Test

Delete Entire child element node

public void Delete1 () throwsparserconfigurationexception, Saxexception, IOException, transformerexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

element element = (Element) document.getelementsbytagname ("Price"). Item (2);

Element.getparentnode (). Getparentnode (). RemoveChild (Element.getparentnode ());

Transformerfactory TFF =transformerfactory.newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (new Domsource (document), Newstreamresult (New FileOutputStream ("Src/book.xml"));

}

@Test

modifying nodes

public void Update () throwsparserconfigurationexception, Saxexception, IOException, transformerexception{

Documentbuilderfactory factory =documentbuilderfactory.newinstance ();

Documentbuilder db =factory.newdocumentbuilder ();

Document document = Db.parse ("Src/book.xml");

element element = (Element) document.getelementsbytagname ("Price"). Item (0);

Element.settextcontent ("80 Yuan"); Set value with this method, you cannot use Element.setnodevalue ()

Transformerfactory TFF = Transformerfactory.newinstance ();

Transformer tf = Tff.newtransformer ();

Tf.transform (new Domsource (document), Newstreamresult (New FileOutputStream ("Src/book.xml"));

}

}

Two: Sax parsing the document, sax can only query the document, can not add to the XML document. But it reads the edge parse, fast

package Com.dom;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import Javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import Org.xml.sax.XMLReader;

import Org.xml.sax.helpers.DefaultHandler;

Publicclass Demo3 {

publicstaticvoid Main (string[] args)throws Parserconfigurationexception,

Saxexception, IOException {

Create a factory class

SAXParserFactory SPF = saxparserfactory.newinstance ();

To create a SAX parser

SAXParser sp = Spf.newsaxparser ();

Get reader

XMLReader XR = Sp.getxmlreader ();

Setting up the processor

Xr.setcontenthandler (new Bookcontenthandler ());

reading XML files

Xr.parse ("Src/book.xml");

}

}

This processor class that you write yourself must be a default or public external class, not an inner class (because the DefaultHandler class is inherited) and cannot be private (inaccessible)

class Bookcontenthandlerextends defaulthandler {

@Override

publicvoid characters (char[] ch,int start,int length)

throws saxexception {

System.out.println (new String (CH, start, length));

}

@Override

publicvoid endelement (String uri, String localname, String qName)

throws saxexception {

System.out.println ("<" + QName + ">");

}

@Override

publicvoid startelement (String uri, String localname, String qName,

Attributes Attributes) throws saxexception {

System.out.println ("<" + QName + ">");

}

}

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.