Dark Horse Day01 (c) Parsing method of XML

Source: Internet
Author: User
Tags xml document reader

XML programming: Using Java programs to remove and delete data from a modified (CRUD) XML

Analytic thought:
Dom parsing
Sax parsing
Based on these two analytical ideas, there are a lot of analytic APIs on the market.
Sun Jaxp has both Dom and sax, and this parsing API has been added to the J2SE specification, meaning that this parsing can be directly used without the need to import any third-party development packages. But this kind of parsing is inefficient, and no one uses it.
DOM4J can parse XML efficiently using the DOM approach.
Pull

!! dom4j

Import the development package, usually only need to import the core package can be, if you are using the process to prompt less what package to the Lib directory in the import of missing packages can be

Parse the XML file:

<?xml version= "1.0" encoding= "UTF-8"?>< Bookshelf >   < book publishing house = "Beijing Press" >     < title >java Employment Training course </Title >      < author > Zhang Xiaoxiang </author >      < selling price >50.00 Yuan </price >      < special >20.0 Yuan </special >   </Book >    < book >     < title >javascript Web Development </title > <      author > Zhang Xiaoxiang </author >      < selling >40.00 yuan </Price >   </book > </bookshelf >

Sax parsing methods:

Package Sax;import Javax.xml.parsers.parserconfigurationexception;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;import Org.xml.sax.attributes;import Org.xml.sax.contenthandler;import Org.xml.sax.locator;import Org.xml.sax.saxexception;import Org.xml.sax.xmlreader;import Org.xml.sax.helpers.defaulthandler;public class SaxDemo1 {public static void main (string[] args) throws Exception {// Parser Factory SAXParserFactory factory=saxparserfactory.newinstance ();//sax parser SAXParser parser = Factory.newsaxparser ();// Get reader XmlReader reader = Parser.getxmlreader ();//Register Event Reader.setcontenthandler (new MyContentHander2 ());// Parse XML document Reader.parse ("Book.xml");}} Read the price of the second book class MyContentHander2 extends Defaulthandler{private String elename= "";p rivate int count=0;@ overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception {s Uper.startelement (URI, LocalName, qName, attributes); this.elename=qname;} @Overridepublic void EndElement (STring URI, String localname, String qName) throws Saxexception {super.endelement (URI, LocalName, qName); Elename= "";} @Overridepublic void characters (char[] ch, int start, int length) throws saxexception {super.characters (ch, start, length) if ("title". Equals (Elename) &&++count==2) {System.out.println (new String (Ch,start,length));}} Class Mycontenthander implements contenthandler{@Overridepublic void Setdocumentlocator (Locator Locator) {//TODO auto-generated method stub} @Overridepublic void Startdocument () throws Saxexception {//TODO auto-generated method Stubsy Stem.out.println ("Start reading documents ...."); @Overridepublic void Enddocument () throws Saxexception {//TODO auto-generated method StubSystem.out.println ("End reading document ....");} @Overridepublic void startprefixmapping (string prefix, string uri) throws Saxexception {//TODO auto-generated method stub } @Overridepublic void endprefixmapping (String prefix) throws saxexception {//TODO auto-generated method stub}@ overridepublic void Startelement (String uri, String LocalName, String Qname,attributes atts) throws Saxexception {//TODO auto-generated method StubSystem.out.println ("Discovery start tag," +qname);} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated met Hod stubSystem.out.println ("End exam label," +qname);} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubsy Stem.out.println (New String (CH, start, length));} @Overridepublic void Ignorablewhitespace (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated Meth OD stub} @Overridepublic void ProcessingInstruction (string target, String data) throws Saxexception {//TODO auto-generated method stub} @Overridepublic void Skippedentity (String name) throws Saxexception {//TODO auto-generated Me Thod stub}}

DOM4J parsing:

Package Dom4j;import Java.io.fileoutputstream;import Java.util.list;import org.dom4j.attribute;import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.documenthelper;import org.dom4j.Element; Import Org.dom4j.io.outputformat;import org.dom4j.io.saxreader;import Org.dom4j.io.xmlwriter;import org.junit.Test ;p Ublic class Dom4jdemo {@Testpublic void attr () throws Exception{saxreader reader=new Saxreader ();D ocument doc = READER.R EAD ("Book.xml"); Element rootelement = Doc.getrootelement (); Element attribute = rootelement.element ("book"). AddAttribute ("Publishing house", "Beijing Press"); XMLWriter writer = new XMLWriter (New FileOutputStream ("Book.xml"), Outputformat.createprettyprint ()); Writer.write ( DOC); Writer.close ();} @Testpublic void Add () throws Exception{saxreader reader=new Saxreader ();D ocument doc = Reader.read ("Book.xml"); Element rootelement = Doc.getrootelement ();//create element telement = Documenthelper.createelement ("specials") in thin air; Telement.settext ("20.0 Yuan");//Mount Rootelement.element ("book"). Add (TElement); XMlwriter writer = new XMLWriter (New FileOutputStream ("Book.xml"), Outputformat.createprettyprint ()), Writer.write (doc ); Writer.close ();} @Testpublic void Delete () throws Exception{saxreader reader=new Saxreader ();D ocument doc = Reader.read ("Book.xml"); Element rootelement = Doc.getrootelement (); Element element = Rootelement.element ("book"). Element ("special"); Element.getparent (). Remove (Element); XMLWriter writer = new XMLWriter (New FileOutputStream ("Book.xml"), Outputformat.createprettyprint ()); Writer.write ( DOC); Writer.close ();} @Testpublic void Update () throws EXCEPTION{//DOM4J parser Saxreader reader=new saxreader ();//get documentdocument doc = Reader.read ("Book.xml");//Get root element elements RootElement = Doc.getrootelement (); list<element> elements = rootelement.elements (); Element element = Elements.get (0); Element.element ("Price"). SetText ("50.00 Yuan"); XMLWriter writer = new XMLWriter (New FileOutputStream ("Book.xml"), Outputformat.createprettyprint ()); Writer.write ( DOC); Writer.close ();} @Testpublic void Find () throws ExcEPTION{//DOM4J parser Saxreader reader=new saxreader ();//Get Documentdocument doc = Reader.read ("Book.xml");//Get root element elements RootElement = Doc.getrootelement (); list<element> elements = rootelement.elements (); Element element = Elements.get (1); System.out.println (Element.element ("title"). GetText ());}}



Dark Horse Day01 (c) Parsing method of XML

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.