Processing XML in Java and PHP (Part 1)
implementing practices from IBM's DB2 9 database (in particular its hybrid engine) encountered a lack of information on the processing of XML data available in the form of streams. Wednesday, April 4, 2007
Gay Cruising Pasco County
After searching the internet I came across the Streaming API for XML (STAX) and its documentation in the form of JSR-173. It turned out that Java SE 1.6 interface provides up to him, but there is no implementation. On the
http://stax.codehaus.org/
quickly found that implementation, then I came across yet to implement Sun's (
at https: / / sjsxp.dev.java.net /
) and Bea Weblogic (at
http://dev2dev.bea.com/xml/stax.html ). Since the first of these three is the reference implementation will be used in this tutorial. Regardless of everything I decided to once again check the text stream analysis capabilities with XML for standards Simple API for XML (SAX) and Document Object Model (DOM). It turned out that was stuck in the mistaken belief.
SAX
SAX is considered the fastest and least memory-XML parser. Based on the representation of event-driven, where the opening and closing of each document, a marker of the presence of the text is defined as an event.
Saxa undoubted disadvantage is lack of knowledge about the location of the XML file (the state). It is also quite hard to implement projects in their own interface.
Work with SAXem start by creating a class of reacting to events (for me MyHandler). The following example is based on the code contained in the book J2EE. Vademecum Developer commercially available Helion SA:
package org.f2k.test;
import java.io.IOException;
SAXTest (String xml) {
this (new ByteArrayInputStream (xml.getBytes
DOM parser is that the complex is used to modify the XML, or its representation in a tree object. Its disadvantage is that it is zasobożerny. The entire document is in fact processed in memory computer.
In the case of DOM, we can immediately write our test class: package
org.f2k.test; import java.io.ByteArrayInputStream; import java.io.InputStream;
javax.xml.parsers.DocumentBuilder import;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
DOMTest public class {public
DOMTest (String xml) {
pareserem STAX is developed by BEA. Although his action is based on event-driven XML form, it gives us the knowledge of the position in the document through the iterator. This allows for faster than the DOM deserializację simple objects.
STAX easiest to use is to create a function that will analyze the incident. The following example will implement the processEvent function similar task to the class of test MyHandler SAX:
org.f2k.test package; import java.io. *;
javax.xml.stream import .*;
import javax.xml . stream.events .*;
public class StAXTest {
StringBuffer textBuffer;
static private Writer out;
xmlText String = info.getDB2XmlString ();
System.out.println ("DB2XmlString: \\ n" + xmlText);
http://stax.codehaus.org/
quickly found that implementation, then I came across yet to implement Sun's (
at https: / / sjsxp.dev.java.net /
) and Bea Weblogic (at
http://dev2dev.bea.com/xml/stax.html ). Since the first of these three is the reference implementation will be used in this tutorial. Regardless of everything I decided to once again check the text stream analysis capabilities with XML for standards Simple API for XML (SAX) and Document Object Model (DOM). It turned out that was stuck in the mistaken belief.
SAX
SAX is considered the fastest and least memory-XML parser. Based on the representation of event-driven, where the opening and closing of each document, a marker of the presence of the text is defined as an event.
Saxa undoubted disadvantage is lack of knowledge about the location of the XML file (the state). It is also quite hard to implement projects in their own interface.
Work with SAXem start by creating a class of reacting to events (for me MyHandler). The following example is based on the code contained in the book J2EE. Vademecum Developer commercially available Helion SA:
package org.f2k.test;
import java.io.IOException;
import java.io.OutputStreamWriter;SAXTest {public class
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
StringBuffer textBuffer;
static private Writer out;
public MyHandler() throws UnsupportedEncodingException{
out = new OutputStreamWriter(System.out, "UTF8");
}
public void startDocument() throws SAXException{
nl();
nl ();
emit ("START OF DOCUMENT");
nl ();
emit ("
");
} public void endDocument () throws SAXException {
nl (); emit ("END OF DOCUMENT ");
try {nl ();
out.flush ();
} catch (IOException e) {throw new SAXException
(" IO Exception ", e);}
} public void startElement
( String namespaceURI, String
sname, / / \u200b\u200bshort name
String qname, / / \u200b\u200bfull name
Attributes attrs) throws SAXException {
echoText ();
nl ();
emit ("ELEMENT:");
Enam String sname = / / element name
/ / without taking into account the namespace name
if ("". equals (Enam))
Enam = QName;
emit ("
if (attrs! = null) {
for (int i = 0; and
anama String = attrs.getLocalName (i) / / attribute name
if (" ". equals (Maanam)) anama = attrs.getQName (i);
nl (); <"+eName);
emit ("ATR:");
emit (Maanam); < attrs.getLength(); i++) {
emit ("\\ t \\" ");
emit (attrs.getValue (i)) ;
emit ("\\" ");}
} if (attrs.getLength ()> 0) nl ();
emit (">");
} public void endElement (String namespaceURI, String sname
/ / short name
String qname / /
full name) throws SAXException {
echoText ();
nl ();
emit ("END_OF_ELEM:");
Enam String sname = / / element name
if (" ". equals (Enam))
Enam = qname;
emit ("
");}
public void characters (char buf [], int offset, int len)
throws SAXException{ "+eName+"> String s = new String(buf, offset, len);
if (textBuffer == null) {
textBuffer = new StringBuffer(s);
} else {
textBuffer.append(s);
}
}
// Metody pomocnicze
private void echoText() throws SAXException{
if (textBuffer == null) return;
nl();
emit("CHARS: throws SAXException {try {
out.write (s);
out.flush ();
} catch (IOException e) {throw new SAXException
("IO Exception", e);
}} private void
nl () throws SAXException {String
lineEnd = System.getProperty ("line.separator");
try {out.write (lineEnd);
} catch (IOException e) {throw new SAXException
("IO Exception", e);
}}}
We have a class that supports the event get ready class of a test by which we can provide the String containing XML
org.f2k.test package;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
javax.xml.parsers.SAXParser import, import
javax.xml. parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
SAXTest (String xml) {
this (new ByteArrayInputStream (xml.getBytes
()));}
SAXTest (InputStream stream) {try {
DefaultHandler handler = new MyHandler ();
SAXParserFactory SAXParserFactory.newInstance factory = ();
SAXParser parser = factory.newSAXParser ();
parser.parse (stream, handler);
} catch (Exception e) {e.printStackTrace
();
}}}
We have virtually everything you need for SAX. We can still set for the object factory option to check an XML document by the DTD, etc. But the longer I leave it to developers:)
HOUSE
DOM parser is that the complex is used to modify the XML, or its representation in a tree object. Its disadvantage is that it is zasobożerny. The entire document is in fact processed in memory computer.
In the case of DOM, we can immediately write our test class: package
org.f2k.test; import java.io.ByteArrayInputStream; import java.io.InputStream;
javax.xml.parsers.DocumentBuilder import;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
DOMTest public class {public
DOMTest (String xml) {
this (new ByteArrayInputStream ( xml.getBytes
()));} public
DOMTest (InputStream stream) {try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
DocumentBuilder builder = factory.newDocumentBuilder ();
Document document = builder.parse (stream);
NodeList names = document.getElementsByTagName ("name");
for (int i = 0; i \u0026lt;names.getLength () , i + +) {System.out.println
(names.item (i). getTextContent ());
}} catch (Exception e) {e.printStackTrace
();
}}}
Our
test looks for nodes in an XML document called name and displays their contents.
STAX
pareserem STAX is developed by BEA. Although his action is based on event-driven XML form, it gives us the knowledge of the position in the document through the iterator. This allows for faster than the DOM deserializację simple objects.
STAX easiest to use is to create a function that will analyze the incident. The following example will implement the processEvent function similar task to the class of test MyHandler SAX:
org.f2k.test package; import java.io. *;
javax.xml.stream import .*;
import javax.xml . stream.events .*;
public class StAXTest {
StringBuffer textBuffer;
static private Writer out;
StAXTest(String xml){DB2Xml info = (DB2Xml) result.getObject ("INFO");
this(new ByteArrayInputStream(xml.getBytes()));
}
StAXTest(InputStream stream){
try {
out = new OutputStreamWriter(System.out, "UTF8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
/*Implementation of StAX*/
System.setProperty("javax.xml.stream.XMLInputFactory",
"com.bea.xml.stream.MXParserFactory");
try {
XMLInputFactory inputFactory
= XMLInputFactory.newInstance();
XMLEventReader eventReader
= inputFactory.createXMLEventReader(stream);
while (eventReader.hasNext()){
XMLEvent event = (XMLEvent) eventReader.next();
processEvent(event);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void processEvent(XMLEvent event) throws IOException{
if (event.isStartElement()){
echoText();
nl();
emit("ELEMENT:
emit(((StartElement) event).getName().toString());
emit(">");
}
if (event.isCharacters()){
String s = ((Characters) event).getData();
if (textBuffer==null){
textBuffer = new StringBuffer(s);
} else {
textBuffer.append(s);
}
}
if (event.isEndElement()){ <");
echoText();
nl();
emit("END_OF_ELEM: ";
emit("
");
}
}
// Metody pomocnicze
private void echoText() throws IOException{
if (textBuffer == null) return;
nl ();
emit ("Chars: DB2 9th Below the code that gets the call and collate records:
org.f2k.test package; "+((EndElement) event).getName().toString()+">
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement ;
import java.sql.ResultSet;
import com.ibm.db2.jcc.DB2Xml;
DB2Connector public class String {
="***";
password String user = "db2admin";
String url = "jdbc: db2: / / localhost: 50000/SAMPLE" public
DB2Connector () {try {
Class.forName ("com.ibm.db2.jcc.DB2Driver"). newInstance ();
Connection conn = DriverManager.getConnection (url,
user, password);
PreparedStatement stmt = conn.prepareStatement (
"SELECT INFO FROM MCUSTOMER WHERE CID =?");
/ / should check whether the user of the CID in 1001, there
stmt. SETINT (1, 1001);
ResultSet result = stmt.executeQuery ();
while (result.next ()) {
xmlText String = info.getDB2XmlString ();
System.out.println ("DB2XmlString: \\ n" + xmlText);
/ / For Encoding other than UTF-8 passes the test only STAX
InputStream stream = info.getDB2XmlBinaryStream ("UTF-8");
System.out.println ("\\ n");
System.out.println ("DB2Xml from STAX test: ");
new StAXTest (stream);
System.out.println (" \\ n ");
System.out.println (" SAX DB2Xml from test ");
stream.reset ();
new SAXTest ( stream);
System.out.println ("\\ n");
System.out.println ("DOM DB2Xml from test");
stream.reset ();
new DOMTest (stream);}
result.close ();
conn.Close ();
} catch (Exception e) {e.printStackTrace
();}
} public static void main (String [] args) {new DB2Connector
() ;
}}
Results
STAX parser and SAX should pay as a result of shredded XML structure with descriptions of events. However, DOM should display the name of the client learned from XML (for me Kathy Smith.)
The second part will describe the processing systems XML with PHP. Also, based on data taken from DB2.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment