Generate an XML parser from any data structure to generate SAX events

Source: Internet
Author: User
Tags object readline return string xml parser
xml| generation of xml| Data | In the j2ee1.4 standard textbook, we see an interesting example of generating an XML parser from any data structure to generate a sax event. The data structure can be a text file, PDF documents, and so on. The key is to parse these data sources yourself. Another interesting place is the application of the Observer model. So it's rough to change it and complete it to the test run. The Observer pattern abbreviated UML diagram:



To implement the observed object Parsexmlsubject class:
Package test;

Import java.io.*;
Import Org.xml.sax.helpers.AttributesImpl;
Import org.xml.sax.*;

public class Parsexmlsubject implements XMLReader {
ContentHandler handler;

String NSU = "";
Attributes Atts = new Attributesimpl ();
String rootelement = "AddressBook";
String indent = "\ n";

Public Parsexmlsubject () {

}

Public ContentHandler Getcontenthandler () {
return handler;
}

public void Parse (InputSource input) throws IOException, Saxexception {
try {
Get a efficient reader for the file
Java.io.Reader r = Input.getcharacterstream ();
BufferedReader br = new BufferedReader (r);

Read the file and display it ' s contents.
String line = Br.readline ();

while (null!= (line = Br.readline ())) {
if (Line.startswith ("email:")) {
Break
}
}

if (handler = = null) {
throw new Saxexception ("No content handler");
}

Note:
We ' re ignoring setdocumentlocator (), as
Handler.startdocument ();
Handler.startelement (NSU, RootElement, RootElement, Atts);

Output ("email", line);
line = Br.readline ();
Output ("HTML", line);
line = Br.readline ();
Output ("FirstName", line);
line = Br.readline ();
Output ("LastName", line);
line = Br.readline ();
Output ("Work", line);
line = Br.readline ();
Output ("Home", line);
line = Br.readline ();
Output ("Fax", line);
line = Br.readline ();
Output ("pager", line);
line = Br.readline ();
Output ("cell", line);
Handler.ignorablewhitespace ("\ n". ToCharArray (), 0,//Start index
1//Length
);
Handler.endelement (NSU, rootelement, rootelement);
Handler.enddocument ();
catch (Exception e) {
E.printstacktrace ();
}
}


public void Parse (String systemid) throws IOException, Saxexception {
}


Public Dtdhandler Getdtdhandler () {
return null;
}


Public Entityresolver Getentityresolver () {
return null;
}

Public ErrorHandler Geterrorhandler () {
return null;
}


public boolean getfeature (String name) throws Saxnotrecognizedexception,
saxnotsupportedexception {
return false;
}


Public Object GetProperty (String name) throws Saxnotrecognizedexception,
saxnotsupportedexception {
return null;
}


public void Setcontenthandler (ContentHandler handler) {
This.handler = handler;
}

public void Setdtdhandler (Dtdhandler handler) {
}


public void Setentityresolver (Entityresolver resolver) {
}


public void Seterrorhandler (ErrorHandler handler) {
}


public void Setfeature (String name, Boolean value) throws
Saxnotrecognizedexception, Saxnotsupportedexception {
}


public void SetProperty (String name, Object value) throws
Saxnotrecognizedexception, Saxnotsupportedexception {
}

    void output (string name, String line) throws Saxexception {
   & nbsp;    int tmp = Name.length ();
        int startindex=tmp+1;
        int textlength = Line.length ()-StartIndex;
        String characters = line.substring (Startindex,line.length ()-1);
        Handler.ignorablewhitespace (Indent.tochararray (), 0,//Start index
                                     Indent.length ());
        handler.startelement (NSU, name, name/* "QName"/*, Atts);

Handler.characters (Characters.tochararray (), StartIndex, textlength);
Handler.endelement (NSU, name, name);
}

}

Specific Observer object: Concreateobserver class
Package test;

Import Org.xml.sax.helpers.DefaultHandler;
Import org.xml.sax.*;
public class Concreateobserver extends DefaultHandler {
Public Concreateobserver () {
}

public void Startelement (String uri,
String LocalName,
String QName,
Attributes Attributes)
Throws saxexception{
System.out.println ("startelement:" +localname);
}
public void characters (char[] ch,
int start,
int length)
Throws saxexception{
System.out.println ("characters:");
System.out.print (CH);
System.out.println ();
}
}

Test class: Testmain
Package test;
Import java.io.*;
Import Org.xml.sax.InputSource;
public class Testmain {
Public Testmain () {
}

public static void Main (string[] args) throws Exception {
Testmain Testmain = new Testmain ();
FileReader in = new FileReader (New File ("D:\\addressbookreaderlog01.txt"));

Concreateobserver observer=new concreateobserver ();
Parsexmlsubject parse = new Parsexmlsubject ();
Parse.setcontenthandler (Observer);

Parse.parse (New InputSource (in));
}
}

Test text Document: AddressBookReaderLog01.txt

AddressBookReader01.. /samples/personaladdressbook.ldif
Nickname:fred
Email:fred@barneys.house
Html:true
Firstname:fred
Lastname:flintstone
Work:999-quarry
Home:999-bedrocklane
Fax:888-squawk
Pager:777-pager
Cell:555-cell

Another area that is also interesting is that the specific observer class inherits from DefaultHandler, which is the application of the default adapter pattern.



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.